When you switch from a language with manual memory management, such as C or C++, to a
garbage-collected language, your job as a programmer is made much easier by the fact that
your objects are automatically reclaimed when you're through with them. It seems almost like
magic when you first experience it. It can easily lead to the impression that you don't have to
think about memory management, but this isn't quite true.
Consider the following simple stack implementation:
Code:
// Can you spot the "memory leak"?
public class Stack {
private Object[] elements;
private int size = 0;
public Stack(int initialCapacity) {
this.elements = new Object[initialCapacity];
}
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) {
Object[] oldElements = elements;
elements = new Object[2 * elements.length + 1];
System.arraycopy(oldElements, 0, elements, 0, size);
}
}
}
There's nothing obviously wrong with this program. You could test it exhaustively, and it
would pass every test with flying colors, but there's a problem lurking. Loosely speaking, the
program has a “memory leak,” which can silently manifest itself as reduced performance due
to increased garbage collector activity or increased memory footprint. In extreme cases, such
memory leaks can cause disk paging and even program failure with an OutOfMemoryError,
but such failures are relatively rare.
So where is the memory leak? 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.
Memory leaks in garbage collected languages (more properly known as unintentional object
retentions) are insidious. If an object reference is unintentionally retained, not only is that
object excluded from garbage collection, but so too are any objects referenced by that object,
and so on. Even if only a few object references are unintentionally retained, many, many
objects may be prevented from being garbage collected, with potentially large effects on
performance.
The fix for this sort of problem is simple: Merely null out references once they become
obsolete. In the case of our Stack class, the reference to an item becomes obsolete as soon as
it's popped off the stack.
The corrected version of the pop method looks like this:
Code:
public Object pop() {
if (size == 0) {
throw new EmptyStackException();
}
Object result = elements[--size];
elements[size] = null; // Eliminate obsolete reference
return result;
}
An added benefit of nulling out obsolete references is that, if they are subsequently
dereferenced by mistake, the program will immediately fail with a NullPointerException,
rather than quietly doing the wrong thing. It is always beneficial to detect programming errors
as quickly as possible.
VERY IMPORTANT:
So when should you null out a reference? What aspect of the Stack class makes it susceptible
to memory leaks? Simply put, the Stack class
manages its own memory. The storage pool
consists of the elements of the items array (the object reference cells, not the objects
themselves). The elements in the active portion of the array (as defined earlier) are allocated,
and those in the remainder of the array are free. The garbage collector has no way of knowing
this; to the garbage collector, all of the object references in the items array are equally valid.
Only the programmer knows that the inactive portion of the array is unimportant. The
programmer effectively communicates this fact to the garbage collector by manually nulling
out array elements as soon as they become part of the inactive portion.