Managing resource closure in a servlet container
- by Steven Schlansker
I'm using Tomcat as a servlet container, and have many WARs deployed. Many of the WARs share common base classes, which are replicated in each context due to the different classloaders, etc.
How can I ensure resource cleanup on context destruction, without hooking each and every web.xml file to add context listeners?
Ideally, I'd like something along the lines of
class MyResourceHolder implements SomeListenerInterface {
private SomeResource resource;
{
SomeContextThingie.registerDestructionListener(this);
}
public void onDestroy() { resource.close(); }
}
I could put something in each web.xml, but since there are potentially many WARs and only ones that actually initialize the resource need to clean it up, it seems more natural to register for cleanup when the resource is initialized rather than duplicating a lot of XML configuration and then maybe cleaning up.
(In this particular case, I'm initiating an orderly shutdown of a SQL connection pool. But I see this being useful in many other situations as well...)
I'm sure there's some blisteringly obvious solution out there, but my Google-fu is failing me right now. Thanks!