Java – How does Keep-alive work with ThreadPoolExecutor

javakeep-alivemultithreading

In continuation to a question posted by me, I'm trying to use ThreadPoolExecutor in my codebase. Even after repeated attempts to comprehend from Java API doc, I failed to understand clearly the functionality/purpose behind keepAliveTime parameter to be passed in the constructor. Hope somebody can explain me with some good working example.

Excerpts from Java doc:

public ThreadPoolExecutor(int corePoolSize,
                          int maximumPoolSize,
                          long keepAliveTime,
                          TimeUnit unit,
                          BlockingQueue<Runnable> workQueue)

keepAliveTimewhen the number of threads is greater than the core, this is the maximum time that excess idle threads will wait for new tasks before terminating.

Best Answer

Suppose you have a core size of 5, and a maximum size of 15. For some reason your pool gets busy, and uses all 15 available threads. Eventually you run out of work to do - so some of your threads become idle as they finish their final task. So 10 of those threads are allowed to die.

However, to avoid them being killed off too quickly, you can specify the keep-alive time. So if you specified 1 as the keepAliveTime value and TimeUnit.MINUTE as the unit value, each thread would wait one minute after it had finished executing a task to see if there was more work to do. If it still hadn't been given any more work, it would let itself complete, until there were only 5 threads in the pool - the "core" of the pool.