An obsolete reference is one that is kept around but will never be used, preventing the object it refers to from being eligible for garbage collection, thus causing a memory leak.
Manually Setting to NULL
Nulling out a reference to remove obsolete references to an object is good, but one must not overdo it. The best way to eliminate an obsolete reference is to reuse the variable in which it was contained or to let it fall out of scope.
Lets take a Simple Stack implementation as in effective Java
public Object pop() { if (size == 0) throw new EmptyStackException(); Object result = elements[--size]; elements[size] = null; // Eliminate obsolete reference return result; }
In the above code you can see that the stack size is shrinked when ever a pop operation is carried out and is set to null allowing the garbage collector to access the unused space to reclaim
Using WeakHashMap
WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.
How HashMap Works
// Java program to illustrate // Hashmap import java.util.*; class HashMapDemo { public static void main(String args[])throws Exception { HashMap m = new HashMap(); Demo d = new Demo(); // puts an entry into HashMap m.put(d," Hi "); System.out.println(m); d = null; // garbage collector is called System.gc(); //thread sleeps for 4 sec Thread.sleep(4000); System.out.println(m); } } class Demo { public String toString() { return "demo"; } // finalize method public void finalize() { System.out.println("Finalize method is called"); } }
Output
{demo=Hi} {demo=Hi}
How WeakHashMap Works
// Java program to illustrate // WeakHashmap import java.util.*; class WeakHashMapDemo { public static void main(String args[])throws Exception { WeakHashMap m = new WeakHashMap(); Demo d = new Demo(); // puts an entry into WeakHashMap m.put(d," Hi "); System.out.println(m); d = null; // garbage collector is called System.gc(); // thread sleeps for 4 sec Thread.sleep(4000); . System.out.println(m); } } class Demo { public String toString() { return "demo"; } // finalize method public void finalize() { System.out.println("finalize method is called"); } }
Output
{demo = Hi} finalize method is called { }