When is contextDestroyed called?

java, servletcontextlistener, tomcat

Solution

Through a series of trial and error testing I have found that `contextDestroyed()` is called when;

- The server is `.WAR` is being updated/removed.

- The server is shutdown due to administrator intervention.

- The server is shutdown due to a coding error. Something that would terminate a non-server application termination.

If you are experiencing issue #3, as you are suggesting, I think the best possible course of action is to safely (be sure not to create an infinite loop) call `contextInitialized()` to ensure pools are recreated properly.

Problem

Having implemented a `ContextListener` I can now happily deal with `contextDestroyed` events by closing down my connection pools and flushing my caches etc. I was surprised recently when `contextDestroyed` was called at a time when my server was not being shut down - it seemed to be at some arbitrary time which I have not been able to track down. Is there any defined event or set of circumstances that trigger `contextDestroyed`? Should I ensure that everything I do when `contextDestroyed` is called is reversible? Do I need to make all my pools survive a `destroyed/initialized` cycle? Was I wrong to assume I would only get a `contextDestroyed` when Tomcat was being shut down or my `war` was being replaced?

Original source