Shutdown ExecutorService gracefully in webapp?

情到浓时终转凉″ 提交于 2019-11-27 13:33:08

Shutdown hook is not a good approach in Tomcat because:

  • 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

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.

In addition to what Tomasz suggested you can also use CachedThreadPool

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

So a very good solution would be use CachedThreadPool and shutdown it in ServletContextListener.contextDestroyed().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!