Eliminate obsolete object references

Java is a garbage-collected language, your job as a programmer is “nullify” your reference

Consider the following simple stack implementation:

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) {
elements[size++] = e;

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

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

The program above has a “memory leak” can silently reduce the performance due to increased garbage collector activity or memory footprint => OutOfMemoryError

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.

The solution for this sort of problem is simple: null out references once they
become obsolete.

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

Another common source of memory leaks is caches. One you put object references into a cache, It’s easy to forget that’s is there and leave in the cache after it becomes irrelevant. The simple solution is using WeakHashMap, that the entries will be removed automatically after they become obsolete.

A third common source of memory leaks is listeners and other callbacks. If you implement an API where clients register callbacks but don’t deregister them
explicitly, they will accumulate unless you take some action. The best way to
ensure that callbacks are garbage collected promptly is to store only weak references
to them, for instance, by storing them only as keys in a WeakHashMap.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s