views:

1126

answers:

3

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?

+8  A: 

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

<web-app>
    <!-- Usual stuff here -->
    <listener>
        <listener-class>com.mycompany.MyClass</listener-class>
    </listener>
</web-app>
leonm
+5  A: 

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.

ChssPly76
It is in the "would be nice but I'll live without it" category. I need to save a bunch of servers' statuses that my app is trying to connect to a file(not db) when the app is shutdown and then reload these info when application is started again. If my app tries to connect to a server and it's down, then it marks it as down so that it doesn't have to retry again. Since the queries happen every often, I only mark these statuses in memory, not to the file. Hence when the app is shutdown, it would be nice to remember which servers are down.
I am leaning toward ServletContextListener or JVM hook
Don't use a JVM hook - that's more for Tomcat itself, or for desktop apps. You should definitely prefer a ServletContextListener over a JVM hook.
Steve McLeod
@unknown - based on your comment I'd go with ServletContextListener. While I don't necessarily agree that JVM hook is "for Tomcat itself", in your case you'd want to save your data if your context is stopped (even if Tomcat isn't), so listener is more appropriate.
ChssPly76
+1  A: 

I suggest using ehcache to cache this information. If you use ehcache's persistent store, then when you start Tomcat again, the cached data will still be available.

In effect, this delegates the issue to ehcache, which is optimised for these types of problems.

Steve McLeod