Item 6: Eliminate obsolete object references

Please take a minute to go through the code given below.

/**
 * Example of a memory leak
 * 
 * @author lekhak.tumblr.com
 */
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);
	}
}

Now, spot the memory leak in this code. I’m sure you’ve spotted the exact fault with the code.

The push method inserts an object every time until the capacity is full. While the pop method returns the reference to element in the stack, it never gets rid of the object.

Now the good news is, that java does want you to manage your memory yourself. And you already know it has a very efficient garbage collector. But, you have to signal your garbage collector to come and take the object away. 

The Solution to this memory leak

Here, what you have to do is to dereference the object once you have dealt with it. Since you are returning the reference, you can assign a null to the spot where the object was situated.

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

Since, after a while the reference is lost forever, the garbage collector comes and gets the object.

Advertisements

About Gaurav

I'm Gaurav; friends call me Teddy, n i'm shivi fr my family!! A java enthusiast who likes experimenting with what he knows. View all posts by Gaurav

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

%d bloggers like this: