19

I know that you can set the number of threads to use for all .par operations like so: collection.parallel.ForkJoinTasks.defaultForkJoinPool.setParallelism(parlevel: Int)

But is it possible to set the number of threads to use for just one .par call?

Community
  • 1
  • 1
dave
  • 12,406
  • 10
  • 42
  • 59

2 Answers2

20

In Scala 2.11 you should use parallel collection task support, like this:

parallelCollection.tasksupport = new ForkJoinTaskSupport(
    new java.util.concurrent.ForkJoinPool(parlevel))

parallelCollection.map( ... )

See task support documentation

samthebest
  • 30,803
  • 25
  • 102
  • 142
caiiiycuk
  • 1,466
  • 14
  • 20
17

You could create a block that sets the parallelism level and then execute specific methods within that block:

def withParallelism[A](n : Int)(block : => A) : A = {
  import collection.parallel.ForkJoinTasks.defaultForkJoinPool._
  val defaultParLevel = getParallelism
  setParallelism(n)
  val ret = block
  setParallelism(defaultParLevel)
  ret
}

And then call it as such:

withParallelism(2) {
  (1 to 100).par.map(_ * 2)
}
Submonoid
  • 2,809
  • 2
  • 20
  • 25