SyntaxHighlighter JS

2013-01-20

Java Memory Leak: Obsolete reference

In program

public class Stack {
  private Object[] elements;
  private int size = 0;

  private static final int INIT_SIZE = 16;

  public Stack() {
    elements = new Object[INIT_SIZE];
  }

  public void push() {
    checkSize();
    elements[size++] = e;
  }

  public Object pop() {
    if (size == 0) { throws EmptyStackException(); }
    Object result = elements[--size];
    return result;

  }

  private void checkSize() {
    if (elements.length = size) {
        elements = Arrays.copyOf(elements, 2 * size + 1);
    }
  }
}

The code line
Object result = elements[--size];

is a Java memory leak because even though the size decrements, the obsolete reference to the Object at element[size] still exists in memory.

The fix is to null of the unneeded reference at elements

  public Object pop() {
    if (size == 0) { throws EmptyStackException(); }
    Object result = elements[--size];
    elements[size] = null;

    return result;
  }

Arrays and collections are places where memory leak obsolete references occur often.

No comments:

Post a Comment