Search code examples
javamultithreadingpool

Actual thread creation in thread pool


If I have a fixed size thread-pool, when will it actually call Thread.start() to launch the threads? (Will it launch them when it gets created? Or will it wait until I start submitting tasks?)


Solution

  • If you create a fixed size thread pool like this:

    ExecutorService es = Executors.newFixedThreadPool(5);
    

    No threads are initially created. When you submit the first task, only 1 thread is created (it is named i.e. "pool-1-thread-1".

    For each additional submitted task, a new thread is created up to the specified fixed size (5 in this example), even if the tasks are not actually running in parallel.

    If, for example, you only submit 3 tasks, only 3 threads will be created with the following names: pool-1-thread-1 pool-1-thread-2 pool-1-thread-3

    This optimization is important since creating a new thread is a resource-heavy operation.

    Any thread that is not currently executing a task is put in wait mode using the LockSupport.Park method.

    When all threads are busy executing tasks, additional submitted tasks are put in a blocking queue where they wait for a thread to become available.

    So to answer your question, the threads only start running when the tasks are first submitted.

    This information is true for JDK 7. I haven't checked other implementations.