2

http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/#javaexample

The Author across the code says that there is memory leakage.

public class LeakExample {
    static Vector myVector = new Vector();
    static HashSet pendingRequests = new HashSet();

    public void slowlyLeakingVector(int iter, int count) {
        for (int i=0; i<iter; i++) {
            for (int n=0; n<count; n++) {
                myVector.add(Integer.toString(n+i));
            }
            for (int n=count-1; n>0; n--) {
                // Oops, it should be n>=0
                myVector.removeElementAt(n);
            }
        }
    }

How does this code has memory leak and while the below does not have. What makes both different.

public void noLeak(int size) {
        HashSet tmpStore = new HashSet();
        for (int i=0; i<size; ++i) {
            String leakingUnit = new String("Object: " + i);
            tmpStore.add(leakingUnit);
        }
        // Though highest memory allocation happens in this
        // function, but all these objects get garbage
        // collected at the end of this method, so no leak.
    }

3 Answers 3

6

In your first example, not all the elements of the vector are removed (as is shown by the comment in the code). And since myVector is a static member variable, it stays there for as long as the app is running, and will grow over time with each call to slowlyLeakingVector().

In the second example, tmpStore is a local variable, which will be garbage collected every time after returning from noLeak().

Sign up to request clarification or add additional context in comments.

Comments

2

Every time the first code is run, n elements are added, and (n-1) are removed (the element at 0 is not) so the vector slowly stores elements that will never be used. And as the vector is static, it will exist until the JVM is shut down, leaking memory.

In the second example, the tmpStore can be garbage collected at the end of each call, so no leak.

Comments

1

The key here is

for (int n=count-1; n>0; n--) {
    // Oops, it should be n>=0
    myVector.removeElementAt(n);
}

Last element never gets removed as n is never 0 inside the loop, ie removeElementAt(0) never runs. This leads to the elements slowly accumulating in the vector.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.