java web 内存泄露,使用ScheduledExecutorService时Java Webapp内存泄漏

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.

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();

}

}

.. 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();

}

}

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

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 ?

解决方案

Calling fScheduler.shutdownNow(); is not enough:

There are no guarantees beyond best-effort attempts to stop processing actively executing tasks.

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

fScheduler.shutdownNow();

fScheduler.awaitTermination(10, TimeUnit.SECONDS);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值