newCachedThreadPool 线程池为何要移除超时的线程?

2017-08-08 11:21:43 +08:00
 guyeuro

对于 newCachedThreadPool 线程池,我看到的说法是:

“如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。“

为何不 reuse 这些超时的线程,而要去新创建一个线程添加到池中?这样不是性能更低么?

1869 次点击
所在节点    问与答
6 条回复
Monstercat
2017-08-08 11:27:18 +08:00
开太多线程也会影响性能
lovedebug
2017-08-08 11:31:36 +08:00
挂起的线程可能永远不退出怎么办? 线程池最后可能没有可用线程了。
guyeuro
2017-08-08 11:38:15 +08:00
@lovedebug 我意思,既然要创建一个新线程加到池中,为何不干脆 reuse 那些超时的线程?
zhaohui318
2017-08-08 12:00:35 +08:00
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool()

Creates a thread pool that creates new threads as needed, but will reuse previously constructed threads when they are available. These pools will typically improve the performance of programs that execute many short-lived asynchronous tasks. Calls to execute will reuse previously constructed threads if available. If no existing thread is available, a new thread will be created and added to the pool. Threads that have not been used for sixty seconds are terminated and removed from the cache. Thus, a pool that remains idle for long enough will not consume any resources. Note that pools with similar properties but different details (for example, timeout parameters) may be created using ThreadPoolExecutor constructors

这是两句话,分开来理解。

有需求时如果有空闲的线程当然会 reuse
正是没要需求,线程才会空闲超时然后被清除来节省内存资源
ihuotui
2017-08-08 12:00:59 +08:00
那就不是用这个类了,不同类的目的不一样。
honeycomb
2017-08-08 12:33:15 +08:00
它是说线程未使用(没有任务)长达 60 秒后抛弃。
楼上的 @zhaohui318 说得很清楚

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/381285

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX