Java 5 – 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

1. SynchronizedMap v/s ConcurrentHashMap :

SynchronizedMap ConcurrentHashMap
This is thread-safe version of MapConcurrentHashMap is newly introduced thread-safe class
Only one thread is allowed to operate on synchronized map, by locking over complete map objectMultiple 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 objectRead 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 thrownWhile one thread iterating ConcurrentHashMap items, other thread are happily can modify Map items


And it never throws ConcurrentModificationException

That’s it is fail-fast iteratorThat’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 keyNULL insertion isn’t allowed for both keys and values
This is introduced in original collection framework in Java 1.2 versionThis is introduced in Java 1.5 version

Q) 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

Q) 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

2. ConcurrentHashMap v/s SynchronizedMap

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

Related Articles:


Happy Coding !!
Happy Learning !!

Java 5 - CopyOnWriteArrayList class
Java 5 - ConcurrentHashMap v/s HashMap