Shutdown ExecutorService gracefully in webapp?

后端 未结 2 1332
梦如初夏
梦如初夏 2020-12-03 05:15

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

2条回答
  •  执笔经年
    2020-12-03 05:40

    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.

提交回复
热议问题