在我的webapp中,我有一些类,用于使用run()例程扩展线程类。关闭tomcat时我遇到了问题所以用catch the error and print the stack trace替换了线程实现。
然而它仍然无效:在我的eclipse控制台中关闭tomcat时,会出现如下日志语句:
org.apache.catalina.loader.WebappClassLoaderBase.clearReferencesThreads The web application [Appname] appears to have started a thread named [Timer-1] but has failed to stop it. This is very likely to create a memory leak.
超时后我总是收到一条消息,tomcat没有响应,我必须手动终止它。
我在我的servlet的init()和destroy()方法中启动它们,如下所示:
public void init() throws ServletException
{
worker = new worker();
worker.schedule();
}
public void destroy()
{
worker.shutdownTimer();
worker = null;
}
方法如下:
private ScheduledExecutorService mScheduler = null;
public void schedule()
{
scheduler = getScheduleService();
scheduler.scheduleAtFixedRate(new Runnable()
{
public void run()
{
//...things to do in the routine
}
},
1, //start after 1 second
10, //wait 10 seconds
TimeUnit.SECONDS);
}
private ScheduledExecutorService getScheduleService()
{
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1, new ThreadFactory()
{
public Thread newThread(Runnable r)
{
Thread thread = new Thread(r);
// allow the JVM to kill the scheduled task
thread.setDaemon(true);
return thread;
}
});
return scheduler;
}
public void shutdownTimer()
{
if (scheduler != null)
scheduler.shutdownNow();
}
在我的调试器中,我可以看到executorservice已经开始跟随线程:
Daemon Thread [Timer-0] Running
Thread [pool-3-thread-1] Running
为什么ExecutorService启动正常的线程池?
当我明确告诉它在我的servlet中将它们关闭时,jvm什么时候仍然有关闭这些线程的问题?