What is the proper way to shutdown threads when tomcat closes? What is the proper way to shutdown threads when tomcat closes? multithreading multithreading

What is the proper way to shutdown threads when tomcat closes?


I would register shutdown hooks in the init() method of the servlet rather than contextDetroyed(), but anyway, why do you need Shutdown hooks in the first place?

Can't you just call SomeClass.updater.shutdown();directly in the contextDestroyed() method ?

EDIT

contextDestroyed() of the listener is to late for the executor service. As stated in the javadoc All servlets and filters will have been destroyed before any ServletContextListeners are notified of context destruction.

whereas overriding the servlet destroy() should be OK as according to the javadoc This method gives the servlet an opportunity to clean up any resources that are being held (for example, memory, file handles, threads...

@Overridepublic void destroy(  ) {        myThreadExecutor.shutdown();        super.destroy(  );}


Calling

LogManager.shutdown();

in the contextDestroyed() method is the first step but the ExecutorService does not close immediately. You are getting the exceptions because the ExecutorService threads are still running after the contextDestroyed() method returns. You need to do:

public void contextDestroyed(ServletContextEvent arg0) {      LogManager.shutdown();    if(LogManager.awaitTermination(10, TimeUnit.SECONDS) == false) {        LogManager.shutdownNow();    }} 

This way the thread pool has closed and stopped all threads when contextDestroyed() exits.