Reputation: 13
I'm looking for a threadpool implementation that will not wait when no threads are immediately available in the pool and instead either resort to a serial execution or somehow else let caller know that some tasks that are scheduled for executions would have to wait until thread pool gets back threads that are currently busy.
The net effect I'm trying to achieve is to have parallel executions when possible and when thread pool is fully saturated execute remaining tasks serially in the current thread - that is, where scheduling attempt has been made - without waiting until threadpool gets back another thread.
While this seems doable, I still feel that doing it right would be a significant amount of work - perhaps mostly testing-wise, making sure that all corner cases are properly addressed, etc).
I'd like to avoid reinventing the wheel if this support is readily available in one form or the other in one of the JDK's threading-related library classes.
If some other widely known libraries like Guava or Apache Commons offer that functionality I'd be curious knowing that too.
Upvotes: 0
Views: 290
Reputation: 111339
You can achieve what you want with the standard ThreadPoolExecutor:
SynchronousQueue
as the queue implementation.ThreadPoolExecutor.CallerRunsPolicy
as the task rejection policy.These two parameters can be set by calling the constructor:
ExecutorService executor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, timeUnit,
new SynchronousQueue<>(), new ThreadPoolExecutor.CallerRunsPolicy())
Upvotes: 2