如果我们在 tomcat 服务器中启动单个线程或多个线程,则会发生内存泄漏

Memory leak if we start a single thread or mutilple threads at server start up in tomcat server

 I called the MyListener class from the web.xml file
<listener>  
  <listener-class>MyListener</listener-class>  
</listener>

import javax.servlet.*;  

public class MyListener implements ServletContextListener{  
  public void contextInitialized(ServletContextEvent event) {  
    try{  
        (new Thread(new SampleProcessor())).start();
    }catch(Exception e){e.printStackTrace();}  
  }  

  public void contextDestroyed(ServletContextEvent arg0) {}  
}  

public class SampleProcessor implements Runnable{

 public void run(){
 //Here we write the code for listening to a JMS Topic
}

} 我有另一个类似于上面的监听器,它正在监听另一个 JMS 主题。 当我停止服务器时,服务器上出现以下错误 错误一: "The web application [/MyServlet] appears to have started a thread named [thread-1] but has failed to stop it. This is very likely to create a memory leak." 错误二: "The web application [/MyServlet] appears to have started a thread named [thread-2] but has failed to stop it. This is very likely to create a memory leak."

为什么会发生错误,我们如何停止线程或如何修复它?

我认为您只需彻底关闭线程即可。

执行方法contextDestroyed(ServletContextEvent sce),并向线程发送信号终止。

如何彻底停止线程:

How to properly stop the Thread in Java?

否则线程被强行杀死

粗略举例(未编译):

public class MyListener implements ServletContextListener{  
  static Thread mythread = null;
  public void contextInitialized(ServletContextEvent event) {  
    try{  
        if ( null == mythread ) {
           mythread = new Thread(new SampleProcessor()));
           mytrhread.start();
       }
    }catch(Exception e){e.printStackTrace();}  
  }  

  public void contextDestroyed(ServletContextEvent arg0) {

       // your stop method here ...
       try{  
        if ( null != mythread ) {
           mythread.cleanStop();
           mytrhread.join();
       }
    }catch(Exception e){e.printStackTrace();}  
   }  
}  

public class SampleProcessor implements Runnable{

 public boolean running = false;
 public void run(){
 //Here we write the code for listening to a JMS Topic
   running = true; 
  }

 public void cleanStop(){
     //handle stopping the process here
      running = false;  // your main thread loop should test this var 
  }
}