Reputation: 19414
If I run the following code:
System.out.println("Common Pool Parallelism: "
+ForkJoinPool.getCommonPoolParallelism());
long start = System.currentTimeMillis();
IntStream.range(0, ForkJoinPool.getCommonPoolParallelism() * 2)
.parallel()
.forEach(i -> {
System.out.println(i +" " +(System.currentTimeMillis() - start) +"ms");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
});
I get (for example) the following output:
Common Pool Parallelism: 3
5 82ms
3 82ms
1 82ms
0 82ms
4 1087ms
2 1087ms
It appears to me as though the common ForkJoinPool is using 4 threads, then they're blocked for a second, then the last two jobs are run.
But as I understand it, the common ForkJoinPool defaults to using Runtime.getRuntime().availableProcessors() - 1 threads, which in my case is 3 so I'd expect to get three jobs printing at ~82ms not 4.
Is it my code or or understanding that's amiss?
ETA: Printing out Thread.currentThread().getId() within the forEach also shows 4 different thread IDs.
Upvotes: 3
Views: 1047
Reputation: 21
The extra thread in your output is main thread. You can check via printing thread name using Thread.currentThread().getName()
System.out.println("Common Pool Parallelism: "
+ForkJoinPool.getCommonPoolParallelism());
long start = System.currentTimeMillis();
IntStream.range(0, ForkJoinPool.getCommonPoolParallelism() * 2)
.parallel()
.forEach(i -> {
System.out.println(i +" "+Thread.currentThread().getName()+" "+" " +(System.currentTimeMillis() - start) +"ms");
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
});
Upvotes: 0