Reputation: 20705
The definition for ExecutorService.newCachedThreadPool()
is
public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(),
threadFactory);
}
It's creating a pool with corePoolSize = 0
, maximumPoolSize = Integer.MAX_VALUE
and an unbounded queue.
However in the doc for ThreadPoolExecutor
it says:
When a new task is submitted in method execute(java.lang.Runnable), and fewer than corePoolSize threads are running, a new thread is created to handle the request, even if other worker threads are idle. If there are more than corePoolSize but less than maximumPoolSize threads running, a new thread will be created only if the queue is full.
So how does corePoolSize = 0
work in this case? Initially, there's 0 thread so although it doesn't say in the doc I assume it will create a new thread for the first task submitted. But then, now that we have 1 thread > corePoolSize = 0, and 1 thread < maximumPoolSize = Integer.MAX_VALUE, according to the above doc "a new thread will be created only if the queue is full", but the queue is unbounded so no new thread will ever be created and we're stuck with 1 thread?
Upvotes: 3
Views: 1421
Reputation: 28289
so no new thread will ever be created and we're stuck with 1 thread?
Not really.
Please notice newCachedThreadPool
uses SynchronousQueue
:
A blocking queue in which each insert operation must wait for a corresponding remove operation by another thread, and vice versa. A synchronous queue does not have any internal capacity, not even a capacity of one.
This means
if there is idle worker thread trying to get task for the queue, the task will be put into the queue successfully and immediatly taken by this idle thread and get executed.
otherwise, this task can not be put into the queue, in other words, the queue is full. Then new thread will be created to execute the task
Upvotes: 5