WeakHashMap is an implementation of Map interface where the memory of the value object can be reclaimed by Grabage Collector if the corresponding key is no longer referred by any section of program. So if key is no longer used in program. its Entry object will be garbage collected irrespective of its usage. Its clear till here
This is different from HashMap where the value object remain in HashMap even if key is no longer referred. We need to explicitly call remove() method on HashMap object to remove the value. calling remove will just remove the entry from map. Its readyness for GC will depend whether it is still used somewhere in program or not.
Please find this coding example explaining above
Usage of WeakHashMap over HashMap as per mine understanding
My understanding is we should go for WeakHashMap only when we want to ensure that value object is reclaimed by Grabage Collector when key is no longer referred by any section of program. This makes program memory efficient Is my understanding correct here?
Usage of WeakHashMap as per JavaDocs , i could spot this statement
This class is intended primarily for use with key objects whose equals methods test for object identity using the == operator.
I did not get what above statement meant and how it contrast with mine understanding of WeakHashMap usage. Actually i did not get how this statement is related to usage of WeakHashMap?
UPDATE:- on further carefully reading below statement the javadocs
An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations.
i am revising my understanding for the benefit of me and others
Usage of WeakHashMap over HashMap as per mine revised understanding
We should go for WeakHashMap only when we want to ensure that key-value pair is removed from map on GC run when key is no longer in ordinary use other than map itself.
Examples are :-
WeakHashMap<Integer, String> numbers = new WeakHashMap<Integer, String>();
numbers.put(new Integer(1), "one");// key only used within map not anywhere else
numbers.put(new Integer(2), "two");
System.out.println(numbers.get(new Integer(1))); // prints "one"
System.gc();
// let's say a garbage collection happens here
System.out.println(numbers.get(new Integer(1))); // prints "null"
System.out.println(numbers.get(new Integer(2))); // prints "null"
Object key = new Object();
m1.put(key, c1);
System.out.println(m1.size());
key = null or new Object() ; // privious key only used within map not anywhere else
System.gc();
Thread.sleep(100);
System.out.println(m1.size());