1

I have a static initialization block where I read data from DB into certain variables, update that data during the lifetime of the application & save it to DB at regular periodic intervals but when the application is unexpectedly/suddently destroyed/ undeployed I want to write back the current state of the variable back to the DB.

How can I implement this with on destroy trigger in Java ?


Edit:

What about the @PreDestroy annotation, could it be useful for my case ?

Rajat Gupta
  • 25,853
  • 63
  • 179
  • 294

1 Answers1

2

Assuming this is a web application, you can implement and register a ServletContextListener. Its contextInitialized method will be called once upon deployment, and contextDestroyed will be called once on undeployment.

However if the container is ungracefully terminated, contextDestroyed still may not have a chance to run.

See this page for an example of setting one up.

Paul Bellora
  • 54,340
  • 18
  • 130
  • 181
  • Yes this is a webapp but since I was doing initization/intial read within a static initization block in a class, I was wondering it would be nice if I could trigger ondestroy within the same class, if possible ?! – Rajat Gupta Mar 30 '12 at 21:47
  • Running startup/shutdown logic based on class loading/unloading seems much less predictable. It's possible you could hook into the class being unloaded but I'm not the one to ask about this. – Paul Bellora Mar 30 '12 at 21:52