我是否必须关心ThreadPoolExecutor的关闭?

时间:2017-02-21 15:40:10

标签: java spring multithreading tomcat

我有一个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关闭或应用程序将停止时)。

我的问题是:我是否必须关心游泳池的关闭?副作用会发生吗? (例如内存泄漏,Tomcat关机时间过长,......)或者它是否坚如磐石?

1 个答案:

答案 0 :(得分:4)

通常优雅地关闭线程池是一种好习惯。 关闭tomcat实例可能需要更长的时间(如果是未完成的工作),但奖励是一个更加管理和安全的应用程序,可以帮助您在未完成的工作中避免未来的故障排除。

由于您已经使用了spring,因此可能需要使用ThreadPoolTaskExecutor来查看托管的spring线程池。