内存泄漏与弹簧ConfigurableApplicationContext [英] memory leak with spring ConfigurableApplicationContext

查看:221
本文介绍了内存泄漏与弹簧ConfigurableApplicationContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public class Tasker {
ConfigurableApplicationContext context;

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


pulic void doSomething(){
//做某事
}

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



$ b public class Caller extends Thread {

public void run(){
Tasker tasker = new塔斯克();
尝试{
tasker.load();
tasker.doSomething();
} finally(){
tasket.close();




$ b //不在我控制范围内的示例驱动程序代码
调用者调用者= new Caller()
caller.start();
caller.stop();

现在的问题是如果somone调用kill线程,我的Spring上下文永远不会关闭,并且它是一个memeory泄漏。如何防止它?



注意:我无法更改驱动程序代码。

解决方案

Thread.stop 是邪恶的并且严重弃用,永远不会被使用。它给线程没有机会自行清理。在你的情况中,很可能是 Tasker.close 方法永远不会被调用,因为线程立即停止 。您可以通过在 Tasker 方法中添加一些记录语句来验证这一点,这些方法可以在实际发生时打印出来。



它最好是使用 Thread.interrupt 来代替,并且该线程中的代码定期检查中断。



<如果这是调用你无法控制的代码,那么你的运气不好,因为这样的代码意味着你无法正确控制你的上下文的生命周期。


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.

解决方案

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.

这篇关于内存泄漏与弹簧ConfigurableApplicationContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆