tomcat下关闭应用,线程未终止

tomcat关闭时,有时候因为各种原因会报线程未关闭的错误。像这样

The web application [/Test] appears to have started a thread named [your Thread] but has failed to stop it. This is very likely to create a memory leak.

我们可以

1.新建一个类实现ServletContextListener,然后重写 contextDestroyed(ServletContextEvent arg0)方法,在它里面关闭后台进程。

2.也可以继承ContextLoaderListener,ContextLoaderListener实现了ServletContextLoader。

3.注意web.xml中配置你自己的这个listener哦。

public void contextDestroyed(ServletContextEvent sce) {  
      destroyThreads();  
}  
private void destroyThreads(){
      final Set<Thread> threads = Thread.getAllStackTraces().keySet();  
      for (Thread thread : threads) {              
      if(thread.getName().equals("your thread identifier")){
           synchronized (this) {  
             try {  
                thread.stop();  
		          return;
             } catch (Exception e) {  
             }  
        }  
    }  
}


经验分享 程序员 微信小程序 职场和发展