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?
The java.lang.Runtime.addShutdownHook(Thread hook) method registers a new virtual-machine shutdown hook.The Java virtual machine shuts down in response to two kinds of events − The program exits normally, when the last non-daemon thread exits or when the exit (equivalently, System.exit) method is invoked, or.
The shutdown hook will keep the JVM running until the hook is terminated (terminated). This also tells us that if we receive a kill -15 pid command, we can wait for the task to finish before shutting down the JVM. it also explains the problem that some applications cannot exit by executing kill -15 pid.
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.
The danger with using addShutdownHook() is that you will likely get a classloader leak which will become apparent when you redeploy you app multiple times.
Because the shutdown hook's class (either a Thread subclass or a Runnable implementation in your webapp) is coming from your webapp's classloader, even after your webapp is undeployed by the container, the shutdown hook will still be registered with the system. This means the entire webapp's classloader cannot be garbage collected.
I'd definitely recommend ServletContextListener.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With