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] {

  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)

        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)

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.

  • \$\begingroup\$ I don't want to hold you back from learning this stuff. Please go on and work on it like you are doing. It will improve your knowledge and skills. On the other side: If you want to process something in parallel in Scala for practical use you will probably use Futures, Actors and reactive streams. Probably you use the Akka Framework (akka.io). I think under the hood of those APIs the Java ThreadPool / Executor stuff is still in use (I think even with the Fork/Join-Algorithm), but you can work with the mentioned top-level APIs which make parallelism much easier. \$\endgroup\$ – user573215 Jul 4 '15 at 9:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.