4

Here is the codes:

import scala.concurrent._
import ExecutionContext.Implicits.global
import scala.concurrent.duration._


val is = 1 to 100 toList
def db = s"${Thread.currentThread}"
def f(i: Int) = Future { println(db) ; 2 * i }

val theFuture = Future.traverse(is)(f _)

Await.result(theFuture, 10.seconds)

I runned it many times, and the result looks like this:

Thread[ForkJoinPool-1-worker-3,5,main]
Thread[ForkJoinPool-1-worker-3,5,main]
Thread[ForkJoinPool-1-worker-3,5,main]
Thread[ForkJoinPool-1-worker-3,5,main]
Thread[ForkJoinPool-1-worker-3,5,main]
Thread[ForkJoinPool-1-worker-1,5,main]
Thread[ForkJoinPool-1-worker-5,5,main]
Thread[ForkJoinPool-1-worker-7,5,main]
Thread[ForkJoinPool-1-worker-7,5,main]
Thread[ForkJoinPool-1-worker-7,5,main]
Thread[ForkJoinPool-1-worker-7,5,main]
Thread[ForkJoinPool-1-worker-7,5,main]
Thread[ForkJoinPool-1-worker-7,5,main]
Thread[ForkJoinPool-1-worker-7,5,main]
Thread[ForkJoinPool-1-worker-7,5,main]
Thread[ForkJoinPool-1-worker-3,5,main]

The pattern is always "Thread[ForkJoinPool-1-worker-"${AnOddNumber}",5,main]". Does anyone have ideas about why the ID for worker is always Odd number instead of Even number?

1 Answer 1

2

You are using the ExecutionContext.Implicits.global execution context. Under the hood, it uses a ForkJoinPool to handle the working threads. This ForkJoinPool was forked by the Scala library developers in order to modify it accordingly to their needs. You can find it here.

See the function named registerWorker. The names for the workers are constructed adding a prefix (which is the variable named workerNamePrefix, by default the value "ForkJoinPool-${POOL_ID}-worker-") with the pool index which is calculated always as an odd number (see line 1712). Thus, this number will always be odd, no matter what. This is due to the implementation, that avoids scanning the array of work queues, treating it instead as a power-of-two hash table (which requires odd indexing for double-hashing. You can check some nice documentation on hash tables to find more about it).

So, you simply get only 1, 3, 5 and 7 as worker numbers since probably you have a 4-cores computer. If you want them to appear more distributed in the output, just add some delay to the work in order to keep the other workers busy also. Like this:

def f(i: Int) = Future { println(db); Thread.sleep(100); 2 * i }

Hope it helped!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.