java中的内存泄漏

Joh*_*ohn 2 java

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

代码中的作者说存在内存泄漏.

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);
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

这段代码如何有内存泄漏,而下面没有.是什么使两者不同.

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.
    }
Run Code Online (Sandbox Code Playgroud)

Pét*_*rök 6

在第一个示例中,并非所有向量元素都被删除(如代码中的注释所示).并且由于它myVector是一个static成员变量,只要应用程序正在运行,它就会一直存在,并且每次调用都会随着时间的推移而增长slowlyLeakingVector().

在第二个例子中,tmpStore是一个局部变量,每次返回后都会被垃圾收集noLeak().