[ACCEPTED]-shutdown hook for java web application-shutdown

Accepted answer
Score: 55

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

    <!-- Usual stuff here -->


Score: 16

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

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

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

Score: 12

As an addition to leonm's answer:

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

See Spring beans factory lifecycle.

Score: 3

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

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

More Related questions