在webapp中正常关闭ExecutorService? [英] Shutdown ExecutorService gracefully in webapp?

查看:525
本文介绍了在webapp中正常关闭ExecutorService?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的webapp中,我使用固定大小的ThreadPool创建了一个使用 ExecutorService 的服务。我在整个应用程序生命周期中重用了相同的 ExecutorService

In my webapp, I created a service that is using an ExecutorService with fixed size ThreadPool. I reuse the same ExecutorService during the whole application lifetime.

private static ExecutorService pool = Executors.newFixedThreadPool(8);

所有在Tomcat中运行,它在向下发出时出现以下错误:

All is running in Tomcat which gives me the following error while shuting down:

appears to have started a thread named [pool-1-thread-1] but has failed to stop it. This is very likely to create a memory leak.

我确实意识到我需要在关闭tomcat之前关闭ExecutorService。 Soms SO线程已经谈到了这一点,但我找不到一个干净的方法来解决这个问题。

I do realize I need to shutdown the ExecutorService before shuting tomcat down. Soms SO thread already speak about this but I could not find a clean way to handle this.

我应该使用 ShutdownHook 正如@ href=\"https://stackoverflow.com/questions/3332832/graceful-shutdown-of-threads-and-executor\">正确关闭线程和执行程序中的@ Tim-bender所建议的那样?或者我应该使用CachedThreadPool吗?

Should I use a ShutdownHook as suggested @Tim-bender in Graceful shutdown of threads and executor ? Or should I use a CachedThreadPool instead?

推荐答案

关闭挂钩在Tomcat中不是一个好方法,因为:

Shutdown hook is not a good approach in Tomcat because:


  • 它会关闭池太晚(关闭时),Tomcat已经警告你关于没有关闭资源

  • it will close the pool too late (on shutdown), Tomcat will already warn you about not closed resources

您实际上想要在取消部署应用程序时关闭该池,以便重新部署工作(否则每个应用程序将创建新池,并且它们将仅在完全关闭时关闭)

you actually want to shutdown that pool when application is undeployed so that redeployment works (otherwise each application will create new pool and they will all be closed only on complete shutdown)

关闭线程池可能需要一些时间(见下文),关闭钩子应该尽可能快

shutting down the thread pool might take some time (see below), shutdown hook should be as fast as possible

更好的地方是 ServletContextListener.contextDestroyed() 。请记住,你必须同时 shutdownNow()池(取消运行并拒绝新任务)和 awaitTermination()到等待已经运行的任务完成并停止所有线程。

Much better place is ServletContextListener.contextDestroyed(). Remember you have to both shutdownNow() the pool (to cancel running and reject new tasks) and awaitTermination() to wait for already running tasks to finish and all threads to stop.

这篇关于在webapp中正常关闭ExecutorService?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆