我正在使用 ScheduledExecutorService
来运行计划线程。
我实现了 ServletContextListener.contextDestroyed
并调用了 ScheduledExecutorService.shutdownNow
和 awaitTermination
。
这是一个例子:
@Override
public void contextDestroyed(ServletContextEvent servletcontextevent) {
pool.shutdownNow(); // Disable new tasks from being submitted
try {
// Wait a while for existing tasks to terminate
if (!pool.awaitTermination(50, TimeUnit.SECONDS)) {
pool.shutdownNow(); // Cancel currently executing tasks
System.err.println("Pool did not terminate");
}
} catch (InterruptedException ie) {
// (Re-)Cancel if current thread also interrupted
pool.shutdownNow();
// Preserve interrupt status
Thread.currentThread().interrupt();
}
}
不过,我从 Tomcat 7 收到以下错误:
SEVERE: The web application [/servlet] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak.
这个日志可以忽略吗?还是我做错了什么?
谢谢
最佳答案
您确定此错误与您的线程池有关吗?根据线程名称“Timer-0”判断,它可能是由某种计时器启动的。
此外,shutdownNow() 应该返回仍在等待终止的任务列表(请参阅 JavaDoc)。如果列表不为空,您可以构建等待更多时间的逻辑。
关于java - Tomcat 7 和 ScheduledExecutorService.shutdown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9930624/