Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 590
Paul Bellora Avatar asked Aug 05 '11 01:08

Paul Bellora


People also ask

What is addShutdownHook?

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.

What is shutdown hook in spring boot?

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.


2 Answers

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.

like image 60
duffymo Avatar answered Sep 21 '22 01:09

duffymo


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.

like image 39
prunge Avatar answered Sep 21 '22 01:09

prunge