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) {
}
}
}
}