Search code examples
javamemory-leaksgarbage-collection

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();
    }
}

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?


Solution

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