How does Keep-alive work with ThreadPoolExecutor?

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)

keepAliveTime - when 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.


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.


Here is some more description from the Javadoc:

<dt>Keep-alive times</dt>
 *
 * <dd>If the pool currently has more than corePoolSize threads,
 * excess threads will be terminated if they have been idle for more
 * than the keepAliveTime (see {@link
 * ThreadPoolExecutor#getKeepAliveTime}). This provides a means of
 * reducing resource consumption when the pool is not being actively
 * used. If the pool becomes more active later, new threads will be
 * constructed. This parameter can also be changed dynamically
 * using method {@link ThreadPoolExecutor#setKeepAliveTime}. Using
 * a value of <tt>Long.MAX_VALUE</tt> {@link TimeUnit#NANOSECONDS}
 * effectively disables idle threads from ever terminating prior
 * to shut down.
 * </dd>
 *

Essentially this just allows you to control the number of threads left in the idle pool. If you make this too small (for what you are doing), you will be creating too many threads. If you make it too large, you will be consuming memory/threads you don't need to.