我的应用程序服务器日志中有错误
严重:Web应用程序似乎已启动名为[MyThread]的线程 但未能阻止它。这很可能会创建一个内存 泄漏。
要解决这个问题,我应该停止My ServletContextListener实现的contextDestroyed方法中的线程。
但我无法理解如何获取我的Thread / Runnable 的引用,以便我可以调用interrupt()。
我的一个解决方案是:将此线程实例放在ServletContext属性中,但不确定它是否是好的做法。 如果您在申请中采用其他方法,请建议。
答案 0 :(得分:0)
在我的应用程序中有一个服务类(MyServiceClass)
在应用程序开始时,从ServletContextListener调用isConfigurationValid()方法,此方法执行以上3个操作。
这个类有一个我的Thread类型的实例变量,它在其私有的initializeThread方法中被赋予了Thread对象。此方法使用双重检查惯用法来确保只创建一个Runnable对象。
现在我为我的线程实例字段提供了一个静态getter方法,并在contextDestroyed方法中使用它来中断我的Thread。 以下是原始代码,如果有任何
,请忽略语法错误MyServiceClass {
Thread thread;
public static boolean isConfigurationValid(){
loadConfigFile(); // private method of same class
validateDBConfiguration();// private method of same class
initializeThread();// private method of same class
}
private static void initializeThread (boolean usePrimaryPort) {
{
if (thread == null){
synchronized (MyServiceClass.class){
if (thread == null){
Thread thread = new Thread();
Thread.start();
}
}
}
return;
}
}
public static Thread getThread(){
return thread;
}
}