Concepts of WeakHashMap

suggest change

Key points:

Weak references: Objects that are reachable only through weak references are cleared on a garbage-collection cycle. The collector does not wait until it needs memory, unlike soft references.

Difference between HashMap and WeakHashMap:

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 in WeakHashMap.

Example :-

public class WeakHashMapTest {
    public static void main(String[] args) {
        Map hashMap= new HashMap();
        
        Map weakHashMap = new WeakHashMap();
        
        String keyHashMap = new String("keyHashMap");
        String keyWeakHashMap = new String("keyWeakHashMap");
        
        hashMap.put(keyHashMap, "Ankita");
        weakHashMap.put(keyWeakHashMap, "Atul");
        System.gc();
        System.out.println("Before: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
        
        keyHashMap = null;
        keyWeakHashMap = null;
        
        System.gc();  
        
        System.out.println("After: hash map value:"+hashMap.get("keyHashMap")+" and weak hash map value:"+weakHashMap.get("keyWeakHashMap"));
    }
}

System.gc() is only a hint, so the weak entry is not guaranteed to disappear on that call. get expunges stale entries, which is why a later lookup can return null after the key has been collected.

Size differences (HashMap vs WeakHashMap):

Calling size() method on HashMap object will return the same number of key-value pairs. size will decrease only if remove() method is called explicitly on the HashMap object.

Because the garbage collector may discard keys at any time, a WeakHashMap may behave as though an unknown thread is silently removing entries. It is possible for size to return smaller values over time. In a WeakHashMap, the size decreases automatically.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents