简体   繁体   English

Spring ConfigurableApplicationContext发生内存泄漏

[英]memory leak with spring ConfigurableApplicationContext

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? 现在的问题是,如果somone调用杀死线程,则我的Spring上下文永远不会关闭,并且会导致内存泄漏。我该如何预防呢?

Note: i cant change driver code. 注意:我无法更改驱动程序代码。

Thread.stop is evil and heavily deprecated and should never, ever be used. Thread.stop是邪恶的,已被严重弃用,永远不要使用。 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 . 在您的情况下,可能从未调用Tasker.close方法,因为Thread 立即停止。 You can verify this by putting in some log statements in your Tasker methods that print out when things actually occur. 您可以通过在Tasker方法中放入一些日志语句来验证这一点,这些语句可以在实际发生时打印出来。

It's vastly preferably to use Thread.interrupt instead, and for the code in that thread to check for the interrupt periodically. 最好使用Thread.interrupt代替,并让该线程中的代码定期检查中断。

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. 如果这是来自无法控制的代码调用,那么您就不走运了,因为这样的代码意味着您无法正确控制上下文的生命周期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM