OldCurmudgeon
OldCurmudgeon

Reputation: 65811

When is contextDestroyed called?

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?

Upvotes: 19

Views: 19730

Answers (2)

glend
glend

Reputation: 1622

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.

Upvotes: 11

MrTux
MrTux

Reputation: 34003

See: http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html

contextDestroyed(ServletContextEvent sce): Receives notification that the ServletContext is about to be shut down.

I.e., it gets called when a web application gets unloaded (e.g., you remove or replace a .war file from the web-apps folder OR unload it using the Tomcat server-manager).

Upvotes: 3

Related Questions