John
John

Reputation: 1189

leakage of memory in java

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

Upvotes: 2

Views: 824

Answers (3)

Nick Fortescue
Nick Fortescue

Reputation: 44193

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.

Upvotes: 2

P&#233;ter T&#246;r&#246;k
P&#233;ter T&#246;r&#246;k

Reputation: 116306

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

Upvotes: 6

rickythefox
rickythefox

Reputation: 6851

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.

Upvotes: 1

Related Questions