简体   繁体   中英

Why this program can cause memory Leak?

Well , i was going through Memory Leaks in Java .

I saw this simple below program where the author says that Memory Leaks are possible with this below program

But could please tell me whats wrong with this program and why it can produce a Memory Leak ??

package com.code.revisited.memoryleaks;


public class StackTest {

    public static void main(String[] args) {
        Stack<Integer> s = new Stack<>(10000);
        for (int i = 0; i < 10000; i++) {
            s.push(i);
        }

        while (!s.isEmpty()) {
            s.pop();
        }

        while(true){
            //do something
        }

    }

}

pop method is removing Integer objects from the Stack . But Integer objects are not de-referenced; this means that they will occupy memory.

Update :

This point is explained in Item 6 of Effective Java : Eliminate obsolete object references

If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects. An obsolete reference is simply a reference that will never be dereferenced again.

The fix for this sort of problem is simple: null out references or remove object from Stack once they become obsolete. In given case pop method will decrement the top reference.

It really depends how the stack is implemented.

If this is Java's stack (java.util.Stack), then it should not happen. The underlying array is dynamic and may have unused slots, but they are explicitly set to null when popping items.

I guess that the stack in your example is not the standard one; It's probably a part of the example, and it illustrates this kind of memory leak. For example, if the pop() method decreases the underlying array index, but doesn't set the array item to null, then the code above should leave 1000 live objects in the heap, although they are probably not needed anymore by the program.

-- Edit --

Did you take the example from http://coderevisited.com/memory-leaks-in-java/ ? If so, note that it also includes a stack implementation, just as I suspected.

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