Reputation: 31
I'm trying to shutdown my application gracefully.So when the application shutdown is triggered, I need to make the shutdown process wait for configured number of seconds, during this time I would still service few requests.
I have been trying to use wait/sleep in the destroy() method, but the context is already destroyed at this point. My understanding is that destroy() would be called by the container. Is it possible to control the destroy method and delay the start of the shutdown process?
Thanks.
Upvotes: 3
Views: 1823
Reputation: 2508
Your given approach will not work.The reason is destroy()
method. Every servlet will has their own destroy()
method.These method is called when the servlet are being unloaded by the container, not when your application is being shutdown.The servlets can be unload when the container will has no use of a servlet.You can have your application running and still your servlet may get unloaded by the container because the container may hav edecided that these servlet are not needed.
Solution: What you may need is a ServletContextListener. ServletContext is associated with your whole application,not just with a single servlet. When your applicaion is being loaded,the contextInitialized()
of ServletContextListener is invoked and when your application is being unloaded, contextDestroyed()
is invoked.So in contextDestroyed()
,you can sleep the threa and perform other task.
@WebListener
public class MyContextListener implements ServletContextListener
{
public void contextInitialized(ServletContextEvent event)
{
System.out.println("\n \n \n \n ServletContext is being initialized..... \n \n \n");
}
//Perform cleanups like removing DB connection.closing session etc. while closing appliction
public void contextDestroyed(ServletContextEvent event)
{
try{
//Sleep this thread.
Thread.sleep(10000);
} catch(Exception ex){ ex.printStackTrace(System.err); }
}
}
Upvotes: 2