How does Keep-alive work with ThreadPoolExecutor?

[亡魂溺海] 提交于 2019-11-27 11:39:51

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.

Dmitry Krivenko

Here is example of code, which demonstrates work of keepAliveTime How does maximumPoolSize of ThreadPoolExecutor works?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!