As in how does weakhashmap understand that a reference to one of its key is obsolete now especially if the key is a String which is pooled?
Simply put, the WeakHashMap is a hashtable-based implementation of the Map interface, with keys that are of a WeakReference type. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use, meaning that there is no single Reference that point to that key.
An entry in a WeakHashMap will be automatically removed by garbage collector when its key is no longer in ordinary use. Mapping for a given key will not prevent the key from being discarded by the garbage collector, (i.e. made finalizable, finalized, and then reclaimed).
Like most collection classes, this class is not synchronized. A synchronized WeakHashMap may be constructed using the Collections.
WeakHashMap is almost the same as HashMap except in the case of WeakHashMap if the object is specified as the key doesn't contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.
You must not use String literals with WeakHashMap (well you can but there would be no point in it):
String myKey = "somekey";
instead you must use:
String myKey = new String("somekey");
In the latter case String is not pooled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With