Previous | Next | Trail Map | Reference Objects | All About Reference Objects

WeakHashMap Class

A WeakHashMap object is like a HashMap object in that it stores key-value pairs where the key is an arbitrary object. But, in a WeakHashMap OBject, the key is referenced by a weak reference object internal to the WeakHashMap object.

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 WeakHashMap object instead of the HashMap and WeakReference objects, 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 a WeakReference object, and you do not have to explicitly set the associated object to null.

Here is the source code for the WeakHash.java class.


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();
   }
 }
}


Previous | Next | Trail Map | Reference Objects | All About Reference Objects