gpt4 book ai didi

java - 如何获取线程引用以在 contextDestroyed 方法中停止它

转载 作者:行者123 更新时间:2023-11-29 08:52:27 27 4
gpt4 key购买 nike

我的应用程序服务器日志中有错误

SEVERE: A web application appears to have started a thread named [MyThread] but has failed to stop it. This is very likely to create a memory leak.

要解决这个问题,我应该在我的 ServletContextListener 实现的 contextDestroyed 方法中停止线程。

但我无法理解如何获取我的 Thread/Runnable 的引用,以便我可以调用 interrupt()。

我的一个解决方案是:将此线程实例放在 ServletContext 属性中,但不确定它是否是好的做法。如果您在申请中采用其他方法,请提出建议。

最佳答案

在我的应用程序中有一个服务类(MyServiceClass)

  1. 加载配置文件
  2. 验证数据库连接
  3. 初始化这个线程

在应用程序开始时,它的 isConfigurationValid() 方法从 ServletContextListener 调用,该方法执行以上 3 个操作。

这个类有一个 Thread 类型的实例变量,它在其私有(private)的 initializeThread 方法中被分配了 Thread 对象。此方法使用双重检查习惯用法来确保只创建一个 Runnable 对象。

现在我已经为我的线程实例字段提供了一个静态 getter 方法,我在 contextDestroyed 方法中使用它来中断我的线程。以下为原始代码,如有语法错误请忽略

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;
}
}

关于java - 如何获取线程引用以在 contextDestroyed 方法中停止它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22095983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com