Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutdown hook for java web application

I need to save some data preferrably when the java web application is stopped, or when tomcat is stopped. how can this be done? Edit: any drawback if I use the jvm shutdown hook?

like image 512
user121196 Avatar asked Oct 11 '09 05:10

user121196


People also ask

What is shut down hook in Java?

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine begins its shutdown sequence it will start all registered shutdown hooks in some unspecified order and let them run concurrently.

How do I shut down JVM?

There are two ways to terminate the JVM instance from the running application: Calling the exit() method, which initiates the JVM normal shutdown sequence: run all registered shutdown hooks; run all uninvoked finalizers; then end the JVM instance. Calling the halt() method, which ends the JVM instance immediately.


2 Answers

Use a class that implements ServletContextListener in your web.xml:

<web-app>     <!-- Usual stuff here -->     <listener>         <listener-class>com.mycompany.MyClass</listener-class>     </listener> </web-app> 
like image 94
leonm Avatar answered Oct 01 '22 11:10

leonm


Why do you want to do it specifically during shutdown? And do you really need to save it (as in "is it absolutely critical?") or would you like to (as in "would be nice but I'll live without it")?

The distinction is important - no matter what method you try (servlet / context listener as suggested by other answers or JVM shutdown hook) there are no guarantees that it will actually be invoked.

Servlet / context listener destroy events would only be triggered during normal (graceful) container shutdown OR during application reload. JVM shutdown hook would be triggered during process interruption as well; however killing a process (or cutting out the power) would obviously trigger neither.

like image 30
ChssPly76 Avatar answered Oct 01 '22 12:10

ChssPly76