Code Optimization : Effective Java Chapter 2 : Item 6: Eliminate obsolete object references

Code Optimization : Effective Java Chapter 2 : Item 6: Eliminate obsolete object references

  • understanding memory leak
  • the more garbage collector runs the more the it will affect the performance due to inceased GC activity.
// 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

  • 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: 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;
}
  • Nulling out object references should be the exception rather than the norm. *- The best way to eliminate an obsolete reference is to let the variable that contained the reference fall out of scope.
  • This occurs naturally if you define each variable in the narrowest possible scope (Item 45).*
  • Whenever an element is freed, any object references contained in the element should be nulled out.