ConcurrentHashMap v/s SynchronizedMap

In this article, we will discuss difference between SynchronizedMap and ConcurrentHashMap classes in detail i.e.; ConcurrentHashMap v/s SynchronizedMap

Lets us move on and discuss key differences between synchronized version of Map and ConcurrentHashMap

 

SynchronizedMap v/s ConcurrentHashMap :

SynchronizedMap ConcurrentHashMap
This is thread-safe version of Map ConcurrentHashMap is newly introduced thread-safe class
Only one thread is allowed to operate on synchronized map, by locking over complete map object Multiple threads are allowed to operate on concurrent map, by locking over portion of map object i.e.; at segment-level or bucket-level
Every operations like read and update requires lock over complete map object before operating on map object Read operation doesn’t require lock but update operation require definitely lock on the portion of map object i.e.; at segment-level or bucket-level
While one thread iterating Map items, if any other thread tries to modify Map items then ConcurrentModificationException is thrown While one thread iterating ConcurrentHashMap items, other thread are happily can modify Map items

And it never throws ConcurrentModificationException

That’s it is fail-fast iterator That’s it is fail-safe iterator
NULL insertion is possible for key but maximum of one null key and any number of null values against any key NULL insertion isn’t allowed for both keys and values
This is introduced in original collection framework in Java 1.2 version This is introduced in Java 1.5 version

 

When to use SynchronizedMap ?

  • This is generally used to convert map object into thread-safe Map object
  • But only one thread is allowed to operate on map object, as lock is required over complete map object
  • So, performance degrades comparatively in a multi-threaded environment
  • So, use this only when it is required to convert into thread-safe version of Map object

When to use ConcurrentHashMap ?

  • This is the best suit to store key-value pairs in a multi-threaded environment
  • And also one thread iterating never stops other threads to modify
  • And it never throws ConcurrentModificationException

ConcurrentHashMap v/s SynchronizedMap

  • there is always a catch between performance and thread-safety
  • Choose wisely for your requirement

 

References:

 

Happy Coding !!
Happy Learning !!

CopyOnWriteArrayList class
ConcurrentHashMap v/s HashMap