Exactly what a Thread Pool in Java doing?

java, multithreading, threadpool

Solution

Yes, at most only 3 threads will be in the pool at once if in fact you are using `Executors.newFixedThreadPool(3)`

The 10,000 tasks are not `Threads` they are simply `Runnables`. A `Thread` has to be started via `Thread#start` to actually create a system thread. Tasks (instances of `Runnable`) are placed in a `BlockingQueue`. Threads from the thread pool will poll the BlockingQueue for a task to run. When they complete the task, they return to the queue to get another. If more tasks are added, then they are inserted into the `BlockingQueue` according to the rules of the implementation of that queue. For most queues this is First-In-First-Out, but a `PriorityQueue` actually uses a `Comparator` or natural ordering to sort tasks as they are inserted.

Problem

Thread Pool like any ExecutorServices, we defined a newFixedPool of size 3. Now I have a queue of around 10000 runnable tasks. For executing the above process I have these doubts - To execute the above process , is the executor will let only 3 threads from the queus of tasks to run in one shot? The Pool will be carrying 3 Threads , and those 3 threads will only be responsible for executing all the 10000 tasks. If it is correct , how a single thread is running different runnable tasks as finally those tasks are as well threads itself , and in the mid of the running of any of the job/tasks , you can assign new responsibility to the Pool Thread.

Original source