user121196
user121196

Reputation: 31060

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?

Upvotes: 40

Views: 47794

Answers (4)

leonm
leonm

Reputation: 6484

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>

Upvotes: 55

sleske
sleske

Reputation: 83635

As an addition to leonm's answer:

If you use Spring, you can use Spring's "lifecycle management" to achieve a similar effect. For example, you can annotate a method in a bean with @PreDestroy to have it invoked automatically on container shutdown. That way, you don't need to put anything into the web.xml.

See Spring beans factory lifecycle.

Upvotes: 12

Steve McLeod
Steve McLeod

Reputation: 52478

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.

Upvotes: 3

ChssPly76
ChssPly76

Reputation: 100806

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.

Upvotes: 16

Related Questions