How Does a Cached Thread Pool Reuse Existing Threads

Marc van Dongen picture Marc van Dongen · Dec 4, 2012 · Viewed 8k times · Source

I've just started looking at Java's Executors class and the newCachedThreadPool( ) method. According to the API, the resulting thread pool reuses existing Thread objects for new tasks.

I'm a bit puzzled how this is implemented because I couldn't find any method in the Thread API that lets you set the behaviour of an existing Thread object.

For example, you can create a new Thread from a Runnable object, which makes the Thread call the Runnable's run( ) method. However, there is no setter method in the Thread API that takes a Runnable as an argument.

I'd appreciate any pointers.

Answer

Tudor picture Tudor · Dec 4, 2012

Basically imagine each thread from the pool doing this:

public void run() {
    while(true) {
        if(tasks available) {
           Runnable task = taskqueue.dequeue();
           task.run();
        } else {
           // wait or whatever
        }
    }
}