Understanding Weak References : WeakHashMap « Collections « Java Tutorial






  1. Reference class is defined in the java.lang.ref package.
  2. Instead of providing variables that directly reference your memory, you create a reference object that indirectly holds a reference to the object.
  3. The reference objects are then maintained in a reference queue (ReferenceQueue), which monitors the references for reachability by the garbage collector.

There are four types of references to objects.

  1. Direct references like you normally use, as in Integer i = new Integer(13), are called strong references and have no special class. The remaining three are soft references (SoftReference), weak references (WeakReference), and phantom references (PhantomReference).
  2. Soft references are like a cache. When memory is low, the garbage collector can arbitrarily free up soft references if there are no strong references to the object. If you are using soft references, the garbage collector is required to free them all before throwing an OutOfMemoryException.
  3. Weak references are weaker than soft references. If the only references to an object are weak references, the garbage collector can reclaim the object's memory at any time-it doesn't have to wait until the system runs out of memory. Usually, it will be freed the next time the garbage collector runs.
  4. Phantom references are special. They allow you to be notified before the garbage collector performs finalization and frees the object. Think of it as a mechanism to perform cleanup.

(Referend from Ivor Horton's Beginning Java 2, JDK 5 Edition by Ivor Horton Wrox Press 2005)









9.31.WeakHashMap
9.31.1.WeakHashMap Class
9.31.2.Understanding Weak References
9.31.3.Demonstrating the WeakHashMap
9.31.4.Create a WeakHashMap with a single element in it
9.31.5.To enable automatically release of the value, the value must be wrapped in a WeakReference object
9.31.6.Implements a combination of WeakHashMap and IdentityHashMap