我的 Tomcat 7 报告我的 web 应用程序中可能存在内存泄漏
SEVERE: The web application [/mywebapp] appears to have started a
thread named [pool-1-thread-1] but has failed to stop it. This is
very likely to create a memory leak.
我的 web 应用程序中有一个长时间运行的任务,它会在 web 应用程序启动时进行初始化。
public class MyContextListener implements ServletContextListener{
Scheduler scheduler = null;
public MyContextListener(){
scheduler = new Scheduler();
}
@Override
public void contextDestroyed(ServletContextEvent arg0) {
scheduler.stop();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
scheduler.start();
}
}
.. 和我的 Scheduler.java
public class Scheduler {
private final ScheduledExecutorService fScheduler;
public Scheduler() {
fScheduler = Executors.newScheduledThreadPool(1);
}
public void start(){
fScheduler.scheduleWithFixedDelay(new Runnable() {
@Override
public void run() {
//Perform some task
}
}, 1, 240, TimeUnit.MINUTES);
}
public void stop(){
fScheduler.shutdownNow();
}
即使我在关闭服务器时调用 scheduler.stop();
,它仍然报告可能存在内存泄漏。
这个应用程序部署在 jelastic.com 上,我发现一旦启动,它运行良好大约两天,然后任务似乎没有运行。日志中也没有异常或错误。
我是不是做错了什么?是否真的存在潜在的内存泄漏?
最佳答案
调用 fScheduler.shutdownNow();
是不够的:
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks.
来自 JavaDoc .
相反,您必须明确等待当前正在运行的任务:
fScheduler.shutdownNow();
fScheduler.awaitTermination(10, TimeUnit.SECONDS);
关于使用 ScheduledExecutorService 时 Java webapp 内存泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9930773/