本文介绍了使用ScheduledExecutorService时Java Webapp内存泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Tomcat 7报告我的Web应用程序中可能存在内存泄漏

My Tomcat 7 is reporting that there may be a memory leak in my webapp

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应用程序时会初始化.

I have a long running task in my webapp that gets initialized when the webapp is started.

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

.. and my 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();,它仍然报告可能存在内存泄漏.

Even though I calling scheduler.stop(); when shutting down the server, its still reporting there could be a memory leak.

此应用程序已部署在jelastic.com上,我发现该应用程序启动后可正常运行约两天,然后任务似乎无法运行.日志中也没有例外或错误.

This app is deployed on jelastic.com and I find that once it is started, it runs well for around two days and then the tasks don't seem to be running. There is no exceptions or errors in the logs too.

我在这里做错什么了吗?真的有潜在的内存泄漏吗?

Am I doing anything wrong here ? Is there really a potential memory leak ?

推荐答案

调用fScheduler.shutdownNow();是不够的:

来自 JavaDoc .

相反,您必须明确地等待当前正在运行的任务:

Instead you must explicitly wait for the tasks that are currently running:

fScheduler.shutdownNow();
fScheduler.awaitTermination(10, TimeUnit.SECONDS);

这篇关于使用ScheduledExecutorService时Java Webapp内存泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 17:28