Monday, July 22

Synchronized HashMap versus Concurrent hashMap

1. Synchronized Map locks the entire Map While concurrent HashMap work on stripped lock principal. It divided the hash bucket in 16 different sub parts. So if one thread is reading one part of the bucket and other thread is writing on a different part , these execution will not be halted. Thus it gives better performance.


==================================================================
2. Concurrent HashMap does not perform well in case size() or contains() methods are invoked.As it requires synchronization on entire hash bucket.




======================================================================
3. If we need to make two operation on synchronized hashMap , calling code needs to be synchronized While same is not required in case of concurrent hashmap.

For example :

if(!synchronizedList.contains(element)){ ---------------------- (1)

     synchronizedList.add(element); -------------------------------(2)

}



this code is quiet common but not thread safe at all. 1 and 2 are synchronized but the time between the call to 1 and then to 2 there is a possibility that thread contention can occur and our thread which did the contains call may change state. To fix this we need to make this block synchronized in our code. Similar issues happen with synchronized map too.



synchronized(synchronizedList){

     if(!synchronizedList.contains(element)){

          synchronizedList.add(element);

    }

}

ConcurrentHashMap solves ths problem by providing atomic putIfAbscent method calls which essentially does this job only.



========================================================================

4. Synchronized hashMap is fail safe So we need to exclusively synchronize to avoid concurrent modification exception. This will affect overall performance. Concurrent HashMap is lenient on this . It allows to iterate over the map even while are part of bucket is being updated. 


=======================================================================

No comments:

Post a Comment