Executors.newWorkStealingPool() allows creating a limited concurrency pool with target parallelism. Under the hood, it seems to create a new ForkJoinPool with default worker creation factory which is defined here.
This factory seems to create new threads until desired concurrency is reached. Why does this pool not allow using a subset of threads from an existing pool to support limited concurrency while still avoiding creation of new threads everytime? I would assume creation of threads is expensive in Java.
Why does this pool not allow using a subset of threads from an existing pool to support limited concurrency while still avoiding creation of new threads everytime?
The Thread
and ThreadFactory
APIs don't allow you to recycle an arbitrary Thread
object. The problem is that the ThreadFactory::newThread
requires an implementation to return a thread with a given Runnable
but the Thread
API only allows the Runnable
to be set by the Thread
constructor.
Fixing this in Thread
would break the model. (What does it mean to replace the Runnable
of a thread that has been started.)
It could in theory be fixed by defining a subclass of Thread
where the actual run()
method runs user-supplied Runnable
in a loop. But it gets complicated .... and you would only be able to recycle instance of that subclass ... not arbitrary threads.