V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
guyeuro
V2EX  ›  问与答

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

  •  
  •   guyeuro · 2017-08-08 11:21:43 +08:00 · 1815 次点击
    这是一个创建于 2461 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

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

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

    6 条回复    2017-08-08 12:33:15 +08:00
    Monstercat
        1
    Monstercat  
       2017-08-08 11:27:18 +08:00 via Android
    开太多线程也会影响性能
    lovedebug
        2
    lovedebug  
       2017-08-08 11:31:36 +08:00
    挂起的线程可能永远不退出怎么办? 线程池最后可能没有可用线程了。
    guyeuro
        3
    guyeuro  
    OP
       2017-08-08 11:38:15 +08:00
    @lovedebug 我意思,既然要创建一个新线程加到池中,为何不干脆 reuse 那些超时的线程?
    zhaohui318
        4
    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
        5
    ihuotui  
       2017-08-08 12:00:59 +08:00 via iPhone
    那就不是用这个类了,不同类的目的不一样。
    honeycomb
        6
    honeycomb  
       2017-08-08 12:33:15 +08:00 via Android
    它是说线程未使用(没有任务)长达 60 秒后抛弃。
    楼上的 @zhaohui318 说得很清楚
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   899 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 23:25 · PVG 07:25 · LAX 16:25 · JFK 19:25
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.