WeakHashMap example in Java

WeakHashMap is a HashTable based implementation of the Map Interface. The keys of the WeakHashMap have weak reference and so an entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use.
Each key object in a WeakHashMap is stored indirectly as the referent of a weak reference. Therefore a key will automatically be removed only after the weak references to it, both inside and outside of the map, have been cleared by the garbage collector.

From Java Docs – Java doc
WeakHashMap is intended primarily for use with key objects whose equals methods test for object identity using the == operator. Once such a key is discarded it can never be recreated, so it is impossible to do a lookup of that key in a WeakHashMap at some later time and be surprised that its entry has been removed. This class will work perfectly well with key objects whose equals methods are not based upon object identity, such as String instances. With such recreatable key objects, however, the automatic removal of WeakHashMap entries whose keys have been discarded may prove to be confusing.

WeakHashMap example in Java

Lets have a simple example of the WeakHashMap where we will add some data to the map. Then try to make some of the keys “null” and run a garbage collector. Then we will print the WeakHashMap to see the contents.


As you can see that we made the 2 keys – key1 and key3 = null and then called the System.gc() . After that when we printed the WeakHashMap, we can see only 2 elements present.
WeakHashMap example in Java

It's only fair to share...Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedIn