javaapplication-shutdownservlet-listeners

contextDestroyed() vs addShutdownHook()


I'm currently implementing ServletContextListener and using contextDestroyed() to run cleanup tasks on my web application before it shuts down. However, I've been reading about how Runtime.addShutdownHook(Thread) can be used for the same purpose.

Is there any difference between these two methods of running cleanup before undeployment? Which is preferable for a web application, in terms of functionality, efficiency, and maintainability?


Solution

  • I think the ServletContextListener is more appropriate for a web application, because you clean up resources for each and every session.

    A shutdown hook is executed with the JVM is shut down. That would be when you stop your container, which is a one-time event.