Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I am a newbie trying to learn some Java and I am reading prof. Dan Grossman's introductory lecture notes on parallel and concurrent algorithms.

I wrote a version of a divide-and-conquer algorithm for summing an array of integers using both bare-bones Java Threads and one that uses the new (in Java 7) Fork/Join framework.

Since I am learning things, just for fun I tried the same summing array in Scala, but I feel that my implementation could use a lot of improvements (I am even more of a newbie in Scala than I am in Java, which says a lot).

package cc.cynic.jvmtests.threading

import java.util.concurrent.{ ForkJoinPool, RecursiveTask }

class ScalaSumArray(val lo: Int, val hi: Int, val arr: Array[Int]) extends RecursiveTask[Int] {
  val SEQUENTIAL_THRESHOLD = 1

  def mysum(lo: Int, hi: Int) = {
    val r = lo until hi
    (for (i <- r) yield arr(i)).sum
  }

  def compute: Int = {
      if (hi - lo <= SEQUENTIAL_THRESHOLD)
        mysum(lo, hi)
      else {
        val left = new ScalaSumArray(lo, (lo + hi) / 2, arr)
        val right = new ScalaSumArray((lo + hi) / 2, hi, arr)

        left.fork()
        val rightans = right.compute()
        val leftans = left.join()
        leftans + rightans
      }
  }
}

object ScalaSumArray {
  def main(args: Array[String]) {
    val fjpool: ForkJoinPool = new ForkJoinPool
    val lo = 0
    val hi = 10001
    val r = lo until hi
    val arr: Array[Int] = r.toArray

    // Without parallelism
    val foo = new ScalaSumArray(lo, hi, arr)
    println(foo.mysum(lo, hi))

    // With parallelism
    val s = new ScalaSumArray(lo, hi, arr)
    println(fjpool.invoke(s))
  }
}

The source code for this is available on my Github account, if you wish to see it there. The corresponding Java version is here.

Again, since I am a novice with Scala, Java and parallel programming, I would appreciate any kind of feedback to improve/simplify the code.

share|improve this question

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.