Thursday, July 7, 2016

WeakHashMap in Java with Example. Differences and Similarities in HashMap and WeakHashMap in java

A HashMap maintains the key value pairs of any specific data type or custom classes. And as we know, if we want to have any custom class instances as a Key to our HashMap then the custom class must implement the hashcode() and equals() method as per the contract of these two methods. Hence, the key of a HashMap plays a vital role in creating a HashMap.

As we know the nature of Garbage Collection, if any object in the program is not having any live reference anywhere then it is available for the garbage collection. If in any HashMap we are using such a key that the reference of that key(instance of a class) does not exist anymore anywhere then the garbage collection should remove it from the map and should collect it's garbage but in case of HashMap it is not possible.

It is possible only when the keys of the map are stored in a WeakReference. WeakReference is a class in java.lang.ref package.Hence, a WeakHashMap is a special Map implementation where the keys of the map are stored in a java.lang.ref.WeakReference . By storing the keys in a weak reference, key-value pairs can dynamically be dropped from the map when the only reference to the key is from the weak reference. It means the key-value pair will be garbage collected if there is not other live reference of the key other than WeakReference class.

Program Example:

public class WeakHashMapExample {
    
    public static void main(String[] args) { 

           
        // Creating HashMap and WeakHashMap objects

        Map hashmapObject = new HashMap();
        Map weakhashmapObject = new WeakHashMap();
        
       // Created HashMap and WeakHashMap keys

        String hashmapKey = new String ("hashmapkey");
        String weakhashmapKey = new String ("weakhashmapkey");

      // Created HashMap and WeakHashMap values

        String hashmapValue = "hashmapvalue";
        String weakhashmapValue = "weakhashmapvalue";  

      // Putting key and value in HashMap and WeakHashMap Object

        hashmapObject.put(hashmapKey ,hashmapValue); 
        weakhashmapObject.put(weakhashmapKey ,weakhashmapValue); 

      // Print HashMap and WeakHashMap Object : Before Garbage Collection
       
        System.out.println("HashMap before Garbage Collected :"+ hashmapObject);
        System.out.println("WeakHashMap before Garbage Collected :"+
                            weakhashmapObject);

     // Set HashMap and WeakHashMap Object keys to null

        hashmapKey = null;  
        weakhashmapKey = null;

     // Calling Garbage Collection
        System.gc(); 

    // Print HashMap and WeakHashMap Object : After Garbage Collection
       
        System.out.println("HashMap after Garbage Collected :"+ hashmapObject);
        System.out.println("WeakHashMap after Garbage Collected :"+
                            weakhashmapObject); 
 }
}

Output:

HashMap before Garbage Collected :{hashmapkey=hashmapvalue}
WeakHashMap before Garbage Collected :{weakhashmapkey=weakhashmapvalue}
HashMap after Garbage Collected :{hashmapkey=hashmapvalue}
WeakHashMap after Garbage Collected :{}


From the above example it is clear that the entry of WeakHashMap is garbage collected if it does not find any strong reference of it but this is not there in HashMap implementation.

Differences in HashMap and WeakHashMap:

1) Entry object Garbage Collected in WeakHashMap but in HashMap Entry object is not Garbage Collected even if the references are set to null.
2) Automatic Size decrease happens in case of WeakHashMap when run the size() method repeateadly on the WeakHashMap as the garbage collection might decrease the count and remove silently the element which is not strongly referenced. But in case of HashMap size() returns the same value until we remove any element explicitly.
3) Clone and Searilize methods are not in WeakHashMap as this class does not implement Cloneable and Serializable interfaces. Rather these methods are present in HashMap as HashMap implements these interfaces.

Similiarities in HashMap and WeakHashMap:

1) Both can have Null Key and Null Value.
2) Performance is similar in both the classes.
3) Both are not synchronized and can be made synchronized by using Collections.synchronizedMap().
4) Iterators of both the classes are fail-fast.

No comments:

Post a Comment