bn.
bn.

Reputation: 7939

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?

Upvotes: 14

Views: 7234

Answers (1)

Brian Goetz
Brian Goetz

Reputation: 95336

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.

Upvotes: 32

Related Questions