How Threadpool re-use Threads and how it works

Jayesh picture Jayesh · Nov 4, 2013 · Viewed 16.7k times · Source

My multithreading concepts are weak and trying to learn.

In Java what I know is, we can't call a thread more than once:

Thread t = new Thread; //Some Runnable
t.start();

t.start(); //Illegal and throw Exception at runtime.

As far as I know, it throws exception when you call t.start() again because the associated stack for the thread is destroyed once it goes out of run() method and you are trying to initialize things again.

In that case, what I know about thread pool is, it gives better performance & saves time because there is no need to create new thread (I read in this).

If there is no need to create new thread in thread pool scenario, then how it works with same thread which just finished its run method, will that thread can be used again?

I read this, and it says that "Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks."

So what is Worker thread here, is it something different then normal Java threads?

With this link, I got something but still confused on what kind of stuff can be eliminated when we use thread pool and why it gives better performance than using normal java threads.

So can we say like this,

Thread has three parts,

  1. Creation (Telling OS that it is new thread, create stack for it.)
  2. Execute Runnable with run() method.
  3. Destroying threads.

So, considering above 3 steps, With thread pool step 1 and step 3 can be eliminated after fixed number of thread creation. Only step 2 for each task will be executed that is why threadpool is faster? Can we say like this? Am I correct?

Answer

Jon Skeet picture Jon Skeet · Nov 4, 2013

If there is no need to create new Thread in ThreadPool scenario, then how it works with same thread which just finished its run method, will that Thread can be used again?

Simple - the original thread never actually completes. It just waits for another task to execute. In pseudo-code:

// No, this isn't even slightly accurate! General impression only :)
while (!pool.isShutdown()) {
    Runnable task = pool.waitForTaskOnQueue();
    task.run();
}

(Obviously when a thread pool is shut down, it would need to stop waiting threads from waiting for another task, too - but hopefully you get the general idea.)