我最近遇到了一个问题,那就是在webachive中停止后台线程。我目前将其绑定到war的部署中,并在未部署归档文件时将其销毁。
线程启动时没有问题,但当我关闭归档时,它似乎失去了线程上的句柄。在以下情况下:当调用contextDestroyed方法时,st为null。
这是一个问题,因为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();
}
}
}发布于 2011-03-07 02:58:30
在contextInitialized方法中,您将st重新声明为局部变量,而不是使用线程初始化实例变量。
替换
SwiftThread st = new SwiftThread(lor);使用
this.st = new SwiftThread(lor);https://stackoverflow.com/questions/5212658
复制相似问题