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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With