Managing resource closure in a servlet container

Posted by Steven Schlansker on Stack Overflow See other posts from Stack Overflow or by Steven Schlansker
Published on 2010-06-15T02:18:31Z Indexed on 2010/06/15 2:22 UTC
Read the original article Hit count: 379

Filed under:
|
|

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!

© Stack Overflow or respective owner

Related posts about java

Related posts about tomcat