zoukankan      html  css  js  c++  java
  • Inspect Memory Leak

    Try to inspect the memory leak in the following code:

    // Can you spot the "memory leak"?
    public class Stack {
    private Object[] elements;
    private int size = 0;
    private static final int DEFAULT_INITIAL_CAPACITY = 16;
    public Stack() {
    elements = new Object[DEFAULT_INITIAL_CAPACITY];
    }
    public void push(Object e) {
    ensureCapacity();
    elements[size++] = e;
    }
    public Object pop() {
    if (size == 0)
    throw new EmptyStackException();
    return elements[--size];
    }
    /**
    * Ensure space for at least one more element, roughly
    * doubling the capacity each time the array needs to grow.
    */
    private void ensureCapacity() {
    if (elements.length == size)
    elements = Arrays.copyOf(elements, 2 * size + 1);
    }
    }

    If a stack grows and then shrinks, the objects that were popped off the stack will not be garbage collected, even if the program using the stack has no more references to them. This is because the stack maintains obsolete references to these objects. An obsolete reference is simply a reference that will never be dereferenced again. In this case, any references outside of the “active portion” of the element array are obsolete. The active portion consists of the elements whose index is less than size.

    public Object pop() {
    if (size == 0)
    throw new EmptyStackException();
    Object result = elements[--size];
    elements[size] = null; // Eliminate obsolete reference
    return result;
    }

    Nulling out obselete references could fix it, but this should be the exception rather than the norm. Also WeakHashMap could be helpful.

  • 相关阅读:
    [ SHOI 2012 ] 随机树
    [ BZOJ 4318 & 3450 / CodeForces 235 B ] OSU!
    [ HNOI 2015 ] 亚瑟王
    [ JSOI 2015 ] Salesman
    [ ZJOI 2007 ] 时态同步
    [ Luogu Contest 10364 ] TG
    [ CodeForces 17 E ] Palisection
    [ BZOJ 2160 ] 拉拉队排练
    Manacher 学习笔记
    [ CodeForces 865 D ] Buy Low Sell High
  • 原文地址:https://www.cnblogs.com/codingforum/p/8447861.html
Copyright © 2011-2022 走看看