memory leak with spring ConfigurableApplicationCon

2019-09-04 11:38发布

问题:

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.