Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call method on undeploy from a Java web-application

I am developing a Java web-application. The application connects to a Lucene index. I create a singleton instance of IndexSearcher. This instance opens some files. When I redeploy the web-application, the files opened by the earlier instance of IndexSearcher continue to remain open, and another instance is created by the redeployed application. After a few redeploys, the system starts throwing a "too many open files" exception. I would like to close the old instance before redeploying, so that the old files are closed, but I cannot figure out how to do that? Is there a directive in web.xml that's called upon un-deploy, similar to load-on-startup? I'm running the web-application on a jboss server.

like image 656
Shashank Agarwal Avatar asked Nov 18 '11 15:11

Shashank Agarwal


2 Answers

Implement a ServletContextListener.

@WebListener
public class LuceneConfig implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        // Do your job here during webapp startup.
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        // Do your job here during webapp shutdown.
    }

}

If you're not on Servlet 3.0 yet (which is already out for 2 years though), then you need to remove the @WebListener annotation and register it manually in web.xml as follows:

<listener>
    <listener-class>com.example.LuceneConfig</listener-class>
</listener>
like image 175
BalusC Avatar answered Oct 14 '22 00:10

BalusC


If you implement javax.servlet.ServletContextListener and register that class in web.xml as a <listener>, then then contextDestroyed() method will be called before the context is unloaded.

like image 26
Ramon Avatar answered Oct 14 '22 00:10

Ramon