1

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?)

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Your question is not very clear to me. – Sid Feb 08 '17 at 17:55
  • Possible duplicate of [How Threadpool re-use Threads and how it works](http://stackoverflow.com/questions/19765904/how-threadpool-re-use-threads-and-how-it-works) – Calculator Feb 08 '17 at 17:55

1 Answers1

1

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.

vstrom coder
  • 297
  • 1
  • 8
  • I think this answer would benefit from some references or supporting details. (Is this behavior specified somewhere? Is it true in all JDK implementations?) – ruakh Feb 08 '17 at 22:25
  • @Gray: I don't understand your comment. Are you saying that you've looked at the source code of a specific JDK implementation and confirmed that vstrom coder's explanation accurately describes the behavior of that implementation? If so, then please consider editing the answer to indicate the specific JDK implementation that you've confirmed it to be correct for (and with links to the relevant code). – ruakh Feb 09 '17 at 21:52
  • Yes I have @ruakh. For example, any sun development kit has the src.zip. The openjdk sources can be received from here: http://download.java.net/openjdk/jdk8/ Unfortunately none of that code is linkable. – Gray Feb 09 '17 at 21:56
  • I guess it is possible for a `Executors. newFixedThreadPool(...)` to not just call a constructor to `ThreadPoolExecutor` or some other class but also to start threads but if so it's a JDK variant I've never seen. – Gray Feb 09 '17 at 21:59