|
|
All About Reference Objects |
AWeakHashMapobject is like aHashMapobject in that it stores key-value pairs where the key is an arbitrary object. But, in aWeakHashMapOBject, the key is referenced by a weak reference object internal to theWeakHashMapobject.After the object referenced by the weak key becomes weakly reachable, the garbage collector clears the internal weak reference. At this point, the key and its associated value become eligible for finalization, and if there are no phantom references to the key, the key and value then become eligible for reclamation. The WeakHashMap class provides a weak hash table facility, but in a class that fits into the new Collections framework.
If you use a
WeakHashMapobject instead of theHashMapandWeakReferenceobjects, you can associate pairs of objects as keys and values. The value is made eligible for garbage collection when the key becomes weakly reachable. This uses fewer lines of code because you do not need aWeakReferenceobject, and you do not have to explicitly set the associated object tonull.Here is the source code for the
WeakHash.javaclass.
Note: This code example works on Solaris, and will be replaced with one that works on all platforms.
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("key: " + aWeakHashMap.containsKey(anObject)); System.out.println(); //Check that the key maps to its value System.out.println("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("key: " + aWeakHashMap.containsKey(anObject)); System.out.println(); //Check whether the key maps to its value System.out.println("Value: " + aWeakHashMap.get(anObject)); } catch (Exception e) { System.err.println("An exception occurred:"); e.printStackTrace(); } } }
|
|
All About Reference Objects |