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.
Asked
Active
Viewed 6,941 times
2 Answers
25
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>

BalusC
- 1,082,665
- 372
- 3,610
- 3,555
-
It works here without registering it. Using Mojarra 2.3.3 on Payara 4.1 (173 build). – Roland Nov 05 '17 at 14:13
-
1Sure it will work fine. Payara 4.x is Servlet 3.1 based. Then the `@WebListener` will work just fine. As answered, it won't work when you're not on Servlet 3.0 yet. The JSF impl/version is irrelevant as it doesn't play a role here. Only the Servlet version is relevant. – BalusC Nov 05 '17 at 14:18
2
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.

Ramon
- 8,202
- 4
- 33
- 41