java util WeakHashMap Class - WeakHashMap Class in Java
WeakHashMap Class in Java
The WeakHashMap functions identically to the HashMap. If the Java memory manager no longer has a strong reference to the object specified as a key, then the entry in the map will be removed. Both null values and the null key are supported.
Is WeakHashMap Thread Safe ?
WeakHashMap is not synchronized.
A synchronized WeakHashMap may be constructed using the Collections.synchronizedMap method.
Is WeakHashMap used for Caching ?
WeakHashMap is not for caching. The idea is, suppose you have a bunch of objects of a certain class that you can't extend, but you want to associate some other piece of information with each object. You can use a Map, with the main object as the key and the extra info as the value. Using a WeakHashMap for this will make sure that your Map won't cause a memory leak, because it won't hold a strong reference to the main (key) object; this will allow the object to be garbage collected when it's no longer needed. When the key is garbage collected, the value will soon be garbage collected too, though not immediately.
java.util.WeakHashMap class Example
java.util.WeakHashMap class Example 2
java.util.WeakHashMap class Example 3
java.util.WeakHashMap class Example 4