Java-堆栈类找不到内存泄漏

时间:2018-07-10 20:59:53

标签: java performance

我在一次采访中遇到了这个问题,并试图在几个小时后解决。 问题是:此堆栈类中存在内存泄漏,请找到并解决。除了达到限制时容量增加一倍的事实之外,我找不到内存泄漏:

public class Stack {

private Object [] elements;
private int size = 0;

public Stack(int initialCapacity) {
    this.elements = new Object[initialCapacity];
}

public void push(Object object) {
    this.ensureCapacity();
    this.elements[size++] = object;
}


public Object pop() {
    if(size == 0)
        throw new EmptyStackException();
    return this.elements[--size];
}

private void ensureCapacity() {

    if(elements.length == size) {

        Object [] old = elements;
        elements = new Object[2 * size + 1];
        System.arraycopy(old, 0, elements, 0, size);
    }
}

public static void main(String[] args) {
    //Before: show memory usage
    Stack stack = new Stack(10000);
    for(int i = 0; i < 10000; i++)
        stack.push("very large String: " + i);
    for(int i = 0; i < 10000; i++)
        System.out.println(stack.pop());        
    // After: show memory usage
}

}

1 个答案:

答案 0 :(得分:5)

这是约书亚·布洛赫(Joshua Bloch)在书Effective Java中给出的示例。内存泄漏在pop函数中,当删除堆栈中的顶部元素时,该引用未设置为null,因此无法对其进行垃圾回收。