1

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.

H-X-P
  • 13
  • 4

1 Answers1

1

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 than corePoolSize 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.

Andreas
  • 154,647
  • 11
  • 152
  • 247
  • According to your answer,if the number of threads are between corePoolSize and maximumPoolSize,we need to iterate all the threads to find the idle thread?could you show me the source code – H-X-P Oct 07 '20 at 07:10
  • I got another explanation from the Internet.It says reuse the idle threads has the cost of lock and the corePoolSize is the optimal solution you choose for your situation,so if threads are less than corePoolSize,create a new thread to avoid the cost of lock,it will help improve performance. Is it right? – H-X-P Oct 07 '20 at 07:20
  • @H-X-P Iterating all the threads requires a lock, so it's really the same explanation, i.e. the cost of checking for an idle thread is just too high. – Andreas Oct 07 '20 at 17:36