How does newCachedThreadPool reuse threads?

Javadoc says the service returned Executors.newCachedThreadPoolis reusing threads. How is this possible? A thread can only be started once by calling start. So how do they implement it? The themes of this service work in an infinite loop, and their Runnable-s are replaced on request?

+5
source share
1 answer

Runnable may call another Runnable.

Each thread starts only one main Runnable, but Runnable accepts Runnables from the general BlockingQueue and calls them until it completes.

This is simplified.

final BlockingQueue<Runnable> queue = ...

Runnable runs = new Runnable() { public void run() {
    while(running)
        queue.take().run();
}};

You can read the code to find out how it does it.

+4
source

All Articles