2011-03-06 61 views
0

我目前有一個問題,在webachive中停止後臺線程。我現在將它與戰爭的部署聯繫起來,並在存檔未部署時將其銷燬。ServletContextListener線程

線程啓動沒有問題,但是當我關閉歸檔時,它似乎失去了線程上的句柄。在以下情況下:調用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(); 
     }  
    } 

} 

回答

1

在你contextInitialized方法,你重新聲明ST作爲一個局部變量,而不是與線程初始化實例變量。

更換

SwiftThread st = new SwiftThread(lor); 

this.st = new SwiftThread(lor); 
+0

哦,天哪,什麼faceplant。就是這個;感謝您指出本應該對我顯而易見的事情。我期待從我的發言中挑選我的分析信心。 – Ken 2011-03-06 19:02:07

相關問題