【问题标题】:ServletContextListener threadsServletContextListener 线程
【发布时间】:2011-03-06 18:55:35
【问题描述】:

我目前在停止 webachive 中的后台线程时遇到问题。我目前将它绑定在战争的部署中,并在档案未部署时将其销毁。

线程启动没有问题,但是当我关闭存档时,它似乎失去了线程的句柄。在以下情况下:当调用contextDestroyed 方法时,st 为空。

这是一个问题,因为 Tomcat 在其有关内存泄漏的警告中指出该线程是孤立的。

public class LimitOrderContextListener implements ServletContextListener {

    static Logger logger = Logger.getLogger(LimitOrderRuntime.class.getName());
    private SwiftThread st = null;

    /**
     * Initializes this listener when this war's context is initialized
     */
    public void contextInitialized(ServletContextEvent sce) 
    {
        try {
            if ( (st == null) || (!st.isAlive()) )  {
                LimitOrderRuntime lor = new LimitOrderRuntime();
                SwiftThread st = new SwiftThread(lor);
                st.start();
            } else {
                st.gracefulStop();
                st.join(2000);
            }
        } catch(Exception e)    {
            logger.warn("Unable to properly load thread! " + 
                    e.getMessage() + " --cause " + e.getCause());
            e.printStackTrace();
        }

    }

    /**
     * When this war is destroyed/stopped, stop the thread.
     */
    public void contextDestroyed(ServletContextEvent sce) 
    {
        try {
            boolean success = st.gracefulStop();
            if (!success)   {
                st.interrupt();
            }
        } catch (Exception e)   {
            logger.warn("Unable to properly release thread! " + 
                    e.getMessage() + " --cause " + e.getCause());
            e.printStackTrace();
        }    
    }

}

【问题讨论】:

    标签: servlets


    【解决方案1】:

    在您的 contextInitialized 方法中,您将 st 重新声明为局部变量,而不是使用线程初始化实例变量。

    替换

    SwiftThread st = new SwiftThread(lor);
    

    this.st = new SwiftThread(lor);
    

    【讨论】:

    • 哦,天哪,真是个面部植物。就是这个;感谢您指出对我来说应该很明显的事情。我期待着恢复我的分析信心。
    猜你喜欢
    • 2016-03-15
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 2013-08-24
    相关资源
    最近更新 更多