控制destroy()方法

时间:2017-04-06 04:39:42

标签: java servlets servletcontextlistener

我正在尝试正常关闭我的应用程序。因此,当触发应用程序关闭时,我需要使关闭进程等待配置的秒数,在此期间我仍然会提供少量请求。

我一直在尝试在destroy()方法中使用wait / sleep,但此时已经破坏了上下文。我的理解是容器会调用destroy()。是否可以控制销毁方法并延迟关机过程的开始?

感谢。

1 个答案:

答案 0 :(得分:2)

你的给定方法不起作用。原因是destroy()方法。每个servlet都有自己的destroy()方法。当卸载servlet时调用这个方法通过容器,而不是当你的应用程序被关闭时。当容器没有使用servlet时,可以卸载servlet。你可以让你的应用程序运行,但是容器可能会卸载你的servlet因为容器可能已经被拒绝了这些servlet不需要。

解决方案:您可能需要的是ServletContextListener。 ServletContext与您的整个应用程序相关联,而不仅仅与单个servlet相关联。在加载应用程序时,将调用ServletContextListener的contextInitialized(),并在卸载应用程序时调用contextDestroyed()。在contextDestroyed()中,您可以睡眠并执行其他任务

    @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); }
        }
    }
相关问题