简体   繁体   中英

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

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

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.

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.

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