【问题标题】:Do I have to care about the shutdown of a ThreadPoolExecutor?我是否必须关心 ThreadPoolExecutor 的关闭?
【发布时间】:2017-02-21 15:40:09
【问题描述】:

我有一个 REST 应用程序(堆栈:Java8/Tomcat7/Spring4.2/Jersey2.15)并在我的 REST 端点中使用一个线程池 (ThreadPoolExecutor)。

      private ThreadPoolExecutor threadPool = (ThreadPoolExecutor) Executors.newFixedThreadPool(10);

端点类配置了spring注解@Component(所以默认是单例)。

在 ThreadPoolExecutor 的 javadoc 中,我读到了这个:

Finalization A pool that is no longer referenced in a program AND has no remaining threads will be shutdown automatically. If you would like to ensure that unreferenced pools are reclaimed even if users forget to call shutdown(), then you must arrange that unused threads eventually die, by setting appropriate keep-alive times, using a lower bound of zero core threads and/or setting allowCoreThreadTimeOut(boolean).

所以当我不调用 threadPool.shutdown() 时,池将在应用程序结束时关闭(通常在这种情况下当 tomcat 关闭或应用程序将停止时)。 p>

我的问题是:我必须关心池的关闭吗?会不会出现副作用? (例如内存泄漏、Tomcat 关闭时间过长……)还是坚如磐石?

【问题讨论】:

    标签: java spring multithreading tomcat


    【解决方案1】:

    优雅地关闭线程池通常是一个好习惯。 关闭您的 tomcat 实例可能需要更多时间(在未完成作业的情况下),但奖励是一个更易于管理和安全的应用程序,并且可能使您免于在未完成作业的情况下进行故障排除。

    由于您已经在使用 spring,您可能希望通过使用 ThreadPoolTaskExecutor 来查看托管 spring 线程池。

    【讨论】:

    • 我想我应该为线程池添加关闭。 spring ThreadPoolTask​​Executor 是这个遗留应用程序未来重构的考虑因素。 ATM线程池的地方太多了,所以我想小步改变。
    • 这是一个真正的挑战!祝你好运!
    猜你喜欢
    • 2021-04-05
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2011-12-26
    • 2015-06-30
    • 2010-11-14
    • 2011-07-02
    • 1970-01-01
    相关资源
    最近更新 更多