When is contextDestroyed called?

OldCurmudgeon picture OldCurmudgeon · Jul 8, 2014 · Viewed 15.7k times · Source

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?

Answer

glend picture glend · Jun 5, 2015

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

  1. The server is .WAR is being updated/removed.
  2. The server is shutdown due to administrator intervention.
  3. 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.