import java.lang.ref.*; import java.util.*; public class WeakHash { public static void main(String[] args) { try { ReferenceQueue aReferenceQueue = new ReferenceQueue(); Object anObject = new Object(); String extraData = new String("Extra Data"); WeakHashMap aWeakHashMap = new WeakHashMap();; //Associate extraData (value) with anObject (key) in aHashMap aWeakHashMap.put(anObject, extraData); //Check whether the key is in the hash map System.out.println("aWeakHashMap key: " + aWeakHashMap.containsKey(anObject)); System.out.println(); //Check that the key maps to its value System.out.println("aWeakhashMap Value: " + aWeakHashMap.get(anObject)); //Clear the strong reference to the key //To make it weakly reachable anObject = null; System.out.println(); //Run the garbage collector System.out.println("*** running gc..."); System.gc(); System.out.println(); //Check whether the Key is in the hash map System.out.println("aWeakHashMap key: " + aWeakHashMap.containsKey(anObject)); System.out.println(); //Check whether the key maps to its value System.out.println("aWeakHashMap Value: " + aWeakHashMap.get(anObject)); } catch (Exception e) { System.err.println("An exception occurred:"); e.printStackTrace(); } } }