joesan
joesan

Reputation: 15385

Scala parallelization method

Having a look at the forall method implementation, how could this method be parallel?

  def forall(p: A => Boolean): Boolean = {
    var result = true
    breakable {
      for (x <- this)
        if (!p(x)) { result = false; break }
    }
    result
  }

As I understand for better parallelization, avoid using var's and prefer val's. How is this now supposed to work if I use forall?

Upvotes: 0

Views: 110

Answers (1)

Beryllium
Beryllium

Reputation: 12998

You are looking at a non-parallel version of forall.

A parallel version looks like this (provided by a parallel collection, in this case ParIterableLike):

def forall(pred: T => Boolean): Boolean = {
  tasksupport.executeAndWaitResult
    (new Forall(pred, splitter assign new DefaultSignalling with VolatileAbort))
}

To get a parallel collection, insert a .par, for example:

List.range(1, 10).par.forall(n => n % 2 == 0)

If you use an IDE like IntelliJ, just "zoom" into that forall, and you'll see the code above. Otherwise here is the source of ParIterableLike (thanks @Kigyo for sharing the URL).

Upvotes: 2

Related Questions