Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is ForkJoinPool.commonPool() equivalent to no pool?

I have determined that using a parallel stream is indeed faster than a serial stream for my data set. With that said, I'm wondering about the ForkJoinPool used as is discussed in this question: Custom thread pool in Java 8 parallel stream.

Given,

void foo()
{
     barCollection.parallelStream()  … do something with the stream
}

are 1 & 2 below equivalent with respect to which pool will be used?

1)

ForkJoinPool.commonPool().submit(()->foo()).get();

2)

foo();

If the answer is yes, then why does the ForkJoinPol.commonPool() method exist?

like image 802
bn. Avatar asked Nov 13 '15 14:11

bn.


1 Answers

Parallel stream execution will use the common pool, but the streams library is merely one possible client of that pool.

As to why the commonPool() method exists, your assumption -- that the common pool exists because of streams -- is incorrect. The common pool exists (and is easy to get to) to prevent the otherwise inevitable "tragedy of the commons" where initiators of parallel operations each creates their own pools, resulting in too many pool threads on a single JVM, undermining efficiency. With a common pool, the path of least resistance -- just use the common pool -- is generally also the best choice.

Parallel streams are one such initiator of parallel operations, and use the common pool, but are not special.

like image 186
Brian Goetz Avatar answered Oct 31 '22 14:10

Brian Goetz