简体   繁体   English

Java中潜在的内存泄漏,这段代码可能会导致内存泄漏吗?

[英]Potential memory leak in Java, may this code lead to the memory leak?

Let say I have a Java code, which constantly runs and every minute should get an array of really heavy objects and proceed them. 假设我有一个Java代码,它不断运行,每分钟都应该得到一个非常重的对象数组并继续它们。 The following code does the job: 以下代码完成了这项工作:

while (true) {

    ArrayList<HeavyObject> objArr = this.getHeavyObject();
    drv.processObject(objArr);

    try {
        Thread.sleep(60000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

My question is: 我的问题是:
May this code lead to the memory leak when executing ArrayList<HeavyObject> objArr = this.getHeavyObject(); 执行ArrayList<HeavyObject> objArr = this.getHeavyObject();时,此代码可能导致内存泄漏ArrayList<HeavyObject> objArr = this.getHeavyObject(); without assigning objArr = null before getting new batch of heavy objects? 在获取新批次的重物之前没有指定objArr = null

According to the « Memory leaks in Java » article it's important to use assigning to null if I don't leave the scope of the variable (this code is a part of the main() and is alive until I exit the program). 根据“ Java中的内存泄漏 ”一文,如果我不离开变量的范围(这段代码是main()的一部分并且在我退出程序之前一直存在main() ,使用赋值为null很重要。

Can you clarify this aspect as applied to the code listed above? 你能否澄清这个方面适用于上面列出的代码?

There will be no leaks in your code as long as the drv object does not maintain references to objArr . 只要drv对象不维护对objArr引用,代码就不会泄漏。 The reference objArr to your "heavy object" is limited to the scope of the while loop, and thus once you leave an iteration, it is eligible for garbage collection. 对你的“重物”的引用objArr仅限于while循环的范围,因此一旦你离开迭代,它就有资格进行垃圾收集。 However, if drv maintains a permanent reference to the object, then it will not be collected as long as the reference persists. 但是,如果drv维护对象的永久引用,则只要引用持续存在,就不会收集它。

The example in the link you mention is when the reference to your data lives outside the scope (in their example, the E[] array field of the Stack class) and cannot be collected. 您提到的链接中的示例是对数据的引用位于范围之外(在其示例中, Stack类的E[]数组字段)并且无法收集。

It does make a difference. 它的确有所作为。

Normally it doesn't matter if you set it to null or to some other value. 通常,如果将其设置为null或其他值,则无关紧要。 Reassigning objArr reduces the reference count and makes it possible to GC the array. 重新分配objArr会减少引用计数,并使GC成为可能。

If, however, the array is so big that you cannot fit two of them in memory at the same time, then it might help, because if you set the reference to null before the call, then the current array can be GC:ed before assigning memory for the next array. 但是,如果数组太大而不能同时将两个数组放在内存中,那么它可能会有所帮助,因为如果在调用之前将引用设置为null,那么当前数组可以是GC:ed之前为下一个数组分配内存。

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

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