Reputation: 13
Suppose a new task is submitted in method execute(),why create a new thread instead of using an existing thread when the number of threads are less than corePoolSize?
public static void main(String[] args) {
ThreadPoolExecutor service = new ThreadPoolExecutor(2, 5, 10L,
TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(3),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
try {
for (int i = 0; i < 8; i++) {
service.execute(() -> {
System.out.println(Thread.currentThread().getName());
});
}
} finally {
service.shutdown();
}
}
I got this question on the Internet. Is it correct? And tell me the reason please.
Upvotes: 1
Views: 619
Reputation: 159135
The question only makes sense if you know this part of the documentation:
Core and maximum pool sizes
[...] When a new task is submitted in method
execute(Runnable)
, and fewer thancorePoolSize
threads are running, a new thread is created to handle the request, even if other worker threads are idle. [...]
The question is, why not use an idle worker thread?
Because we don't know if any of the threads are idle.
Only the threads themselves know that, so we would have to iterate over all the threads to check if there are any idle threads, and that's too expensive when we can just start a new thread and get the thread pool up to its core size.
FYI: You'd have to look at the source code of ThreadPoolExecutor
to learn this.
Upvotes: 1