memory leak with spring ConfigurableApplicationContext

ぐ巨炮叔叔 提交于 2020-01-26 02:08:05

问题


public class Tasker{
    ConfigurableApplicationContext context  ;

    public void load(){
          context = = loadSpringContext();
    }

    pulic void doSomething(){
      //do something
    }

    public  void close(){
       context.close();
    }
}


public class Caller extends Thread {

  public void run(){
    Tasker tasker = new Tasker();
       try{
         tasker.load();
         tasker.doSomething();
       }finally(){
         tasket.close();
       }
  }

}

//sample driver code which is not in my control
Caller caller = new Caller()
caller.start();
caller.stop();

Now the problem is if somone calls kills thread my Spring context is never closed and its a memeory leak.How can i prevent it?

Note: i cant change driver code.


回答1:


Thread.stop is evil and heavily deprecated and should never, ever be used. It gives the thread no chance to clean up after itself. In your case, it's likely that the Tasker.close method is never being called, since the Thread stop immediately. You can verify this by putting in some log statements in your Tasker methods that print out when things actually occur.

It's vastly preferably to use Thread.interrupt instead, and for the code in that thread to check for the interrupt periodically.

If this is from calling code that you can't control then you're out of luck, since such code means you can't control your contexts' lifecycles properly.



来源:https://stackoverflow.com/questions/27769167/memory-leak-with-spring-configurableapplicationcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!