简体   繁体   中英

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. 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(); without assigning objArr = null before getting new batch of heavy objects?

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).

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 . 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. However, if drv maintains a permanent reference to the object, then it will not be collected as long as the reference persists.

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.

It does make a difference.

Normally it doesn't matter if you set it to null or to some other value. Reassigning objArr reduces the reference count and makes it possible to GC the array.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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