[英]How to get thread reference to stop it in contextDestroyed method
I have error in my applications server logs 我的应用程序服务器日志中有错误
SEVERE: A web application appears to have started a thread named [MyThread] but has failed to stop it.
严重:Web应用程序似乎已启动名为[MyThread]的线程,但未能停止它。 This is very likely to create a memory leak.
这很可能造成内存泄漏。
To resolve this i should stop the thread in contextDestroyed method of My ServletContextListener implementation. 为了解决这个问题,我应该在My ServletContextListener实现的contextDestroyed方法中停止线程。
But I am not able to understand how to get reference of my Thread/Runnable so that i can call interrupt(). 但是我不明白如何获取我的线程/可运行对象的引用,以便我可以调用interrupt()。
One solution i have is : putting this thread instance in ServletContext attribute but not sure it is good practice or not. 我有一个解决方案是:将此线程实例放在ServletContext属性中,但不确定是否是好的做法。 Please suggest if you follow some other approach in your application.
请建议您是否在应用程序中遵循其他方法。
In My Application have a service class(MyServiceClass) which 在我的应用程序中有一个服务类(MyServiceClass)
At the start of application its isConfigurationValid() method is called from ServletContextListener and this method does all above 3 operations. 在应用程序开始时,它的isConfigurationValid()方法是从ServletContextListener调用的,并且该方法执行上述所有3个操作。
This class has a instance variable of my Thread type , which is assigned Thread object inside its private initializeThread method. 此类具有我Thread类型的实例变量,该实例变量在其私有的initializeThread方法内分配了Thread对象。 This method is using double check idiom to ensure only one Runnable object is created.
此方法使用双重检查惯用语来确保仅创建一个Runnable对象。
Now I have provided a static getter method for my thread instance field and i interrupt my Thread using this in contextDestroyed method. 现在,我为线程实例字段提供了一个静态getter方法,并在contextDestroyed方法中使用此方法中断了我的线程。 Below is raw code , please ignore syntax errors if any
以下是原始代码,请忽略语法错误(如果有)
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.