Tomcat 7和ScheduledExecutorService.shutdown

lil*_*ili 6 java executorservice tomcat7

ScheduledExecutorService用来运行预定的线程.
我实现ServletContextListener.contextDestroyed并调用了ScheduledExecutorService.shutdownNowawaitTermination.

这是一个例子:

@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();
    }        
}
Run Code Online (Sandbox Code Playgroud)


不过,我从Tomcat 7收到以下错误:

严重:Web应用程序[/ servlet]似乎已经启动了一个名为[Timer-0]的线程,但未能将其停止.这很可能造成内存泄漏.

这个日志可以被忽略吗?或者我做错了什么?

谢谢

max*_*dim 4

您确定此错误与您的线程池有关吗?从线程名称“Timer-0”来看,它可能是由某种计时器启动的。

另外, shutdownNow() 应该返回仍在等待终止的任务列表(请参阅 JavaDoc)。如果列表不为空,您可以构建逻辑来等待更多时间。