WeakHashMap is an implementation of the Map interface, where the memory of a value object can be restored by the Grabage Collector if the corresponding key is no longer transferred by any part of the program. Therefore, if the key is no longer used in the program. Upon its entry, the facility will collect garbage regardless of its use. It's clear so far
This is different from HashMap, where the value object remains in the HashMap, even if the key is no longer being passed. We need to explicitly call remove () on the HashMap object to remove the value. calling remove will simply remove the entry from the card. His readiness for GC will depend on whether he is used somewhere in the program or not.
This code example is explained above.
Using WeakHashMap on top of HashMap as I understand it
My understanding is that we should go for WeakHashMap only when we want the value object to be fixed by the Grabage Collector, when the key no longer refers to any section of the program. This makes program memory efficient. Is my understanding right here?
Using WeakHashMap on JavaDocs , I might notice this statement
This class is primarily intended for use with key objects whose equal methods verify the identity of the object using the == operator.
I did not understand what was meant above, and how this contrasts with my understanding of using WeakHashMap. In fact, I did not understand how this statement is related to the use of WeakHashMap?
UPDATE: - with further careful reading below the javadocs instructions
The entry in the WeakHashMap file is automatically deleted when its key is no longer used in normal mode. 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, completed, completed and then reclaimed. When a key has been discarded, its input is effectively removed from the card, therefore this class behaves somewhat differently than other card implementations.
I am redefining my understanding for the benefit of me and others.
Using WeakHashMap over HashMap as Per My Revised Understanding
We should go for WeakHashMap only when we want to make sure that the key-value pair is removed from the card when the GC starts, when the key is no longer used in the usual way, except for the card itself.
Examples: -
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 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());