WeakHashMap in Java with Code Sample

5
1687

What is WeakHashMap

WeakHashMap is the less common implementation of the MAP interface that stores only weak references in the key.  The memory of the value object can be reclaimed by Garbage Collector if the corresponding key is no longer referred by any section of program. It is also called as special Map implementation or an excellent implementation for a list of weakly referenced values. Reason being, keys which are stored in a weak reference (java.lang.ref.WeakReference), making it one of the few classes able to respond to the fluctuating memory requirements of the JVM.

Elements in a weak HashMap can be reclaimed by the garbage collector if there are no other strong references to the object; this makes them useful for caches/lookup storage.

Understanding Difference in HashMap and WeakHashMap

Before moving ahead lets first understand how WeakHashMap is different from HashMap in different aspects:

Declaration and initialization

  • Map hashMap = new HashMap();
  • Map weakHashMap = new WeahHashMap();

Key / Value reference

The Key and Value is a direct reference by HashMap in case of HashMap Implementation. In WeakHashMap, although value is referenced directly but the key is not refer directly. Instead a WeakReference Object is referenced directly by WeakHashMap, and the key is referenced weakly from the WeakReference object.

Garbage Collection

In HashMap the entry object is not garbage collected as the key has a strong reference. Even if key object has null value. Where as, in WeakHashMap the entry objects are automatically removed when the key is no longer in used.

Cloning and Serialization

HashMap implements Cloneable interface where as WeakHashMap can’t implement Cloaneable Interface. Similarly HashMap implements Serialization where as WeakHashMap doesn’t.

When should we use WeakHashMap

WeakHashmap should be used to reduce the chance of a memory leak as a result of caching some object. Normally it is used to implement ‘cache memory’. If you have some objects that are reused often in your application and their construction is expensive, and there are too many of them to keep them all in memory – you use WeakHashMap. Now keeping them in weakhashmap will use the concept of not holding them directly but via weak reference. So in case the system is running out of memory this will be garbage collected. This means that objects will leave your map as soon as they are no longer used by the rest of your program, which is the desired behavior.

Working Example of  WeakHashMap and HashMap

import java.util.Map;
import java.util.HashMap;
import java.util.WeakHashMap;

public class GoyalsBitWeakHashMapEx {
    
    public static void main(String[] args) { 
              
        Map hashmapObj = new HashMap();
        Map weakhashmapObj = new WeakHashMap();
        
        String hashmapKey = new String ("hashmapkey");
        String weakhashmapKey = new String ("weakhashmapkey");

        hashmapObj.put(hashmapKey ,GoyalsBit HashMap); 
        weakhashmapObj.put(weakhashmapKey , GoyalsBit WeakHashMap); 
   
        System.out.println("HashMap before GC :"+ hashmapObj);
        System.out.println("WeakHashMap before GC:"+   weakhashmapObj);

        hashmapKey = null;  
        weakhashmapKey = null;
        System.gc(); 

	System.out.println("HashMap After GC :"+ hashmapObj);
        System.out.println("WeakHashMap After GC:"+   weakhashmapObj);
 }
}

Output:

HashMap before GC:{hashmapkey= GoyalsBit HashMap }
WeakHashMap before GC:{ weakhashmapKey = GoyalsBit WeakHashMap }

HashMap After GC:{ hashmapkey= GoyalsBit HashMap|

WeakHashMap After GC :{}

So here we saw the difference after garbage collection.

References

http://www.ibm.com/developerworks/library/j-jtp11225/

Oracle’s view on WeakHahMap

Previous articleforEach – Java 8 Feature
Next articleMobile Application Testing
Rahul Goel has 8+ years of experience in IT industry working on design & development of web based applications in Java /JEE technology stack. He posses various business domains knowledge like HealthCare, Banking & Finance, E Commerce, Retail, and Security. Rahul is passionate about cricket, traveling and his technical writing.

5 COMMENTS

  1. Nice Article Rahul…Found it very useful to understand the concept of hash map.
    Your examples are really great and easy to understand. Thanks much !

LEAVE A REPLY