Friday, November 30, 2012

WeakHashMap - Explained

http://docs.oracle.com/javase/6/docs/api/java/util/WeakHashMap.html


What is a WeakHashMap?
  • A WeakHashMap is a HashMap with Weak keys.
Weak Keys:
  • Objects with weak reference to actual objects (Keys)
Weak Reference
  • Weak reference doesn't restrict an object from being garbage collected.
When is an object available for garbage collection?
  • When an object doesn't have any reference (strong) from the program.

Weak references refer to the objects, but the presence of these reference doesn't effect the object's availability for garbage collection.

Once all the strong references to an object are gone, the object becomes available for garbage collection, irrespective of the presence/absence of Weak References to the object.


How does a WeakHashMap work?
1. Keys (weak reference to objects) & Values are inserted.
2. When the objects (keys) doesn't have any strong references, they are garbage collected.
3. Hence, the Keys in HashMap are invalid and hence the corresponding Key-Value pair is deleted.

The WeakHashMap is used for cacheing the objects, where the Entry(Key-Value) will be available only as long as the object itself is available.

Note: The WeakHashMap doesn't use equals() method, but instead uses == while comparing the keys. Since, == directly compares the object address, No two different objects can have the same address, Hence, once an object is deleted, no other object can equal to this object, (So, a new object cannot be constructed to replace the Deleted object). Hence, the keys are deleted.

No comments:

Post a Comment