Java 5 – ConcurrentHashMap v/s HashMap

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

Lets us move on and discuss key differences between these 2 Map classes

1. HashMap v/s ConcurrentHashMap:

HashMapConcurrentHashMap
HashMap is not synchronizedConcurrentHashMap is synchronized
In multi-threaded environment, HashMap is faster than ConcurrentHashMap as multiple threads can operate

 

Hence, performance is high as there is no need to acquire lock

As it is synchronized, lock need to be acquired before operating, although for certain portion of the Map

 

Hence, performance is relatively low when comparing with HashMap

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
While one thread iterating HashMap 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
This is introduced in original collection framework in Java 1.2 versionThis is introduced in Java 1.5 version
We can convert this Map item into synchronized map by using Collections class utility method

 

But still, only one thread is allowed to operate on Map object

There is no such need here, as it is already thread-safe and multiple threads can operate after acquiring bucket-level or segment-level locking strategies

Q) When to use HashMap ?

  • When there are more number of read operations in a multi-threaded environment, then HashMap is very good choice
  • Because reading and updating HashMap object simultaneously by different threads in a multi-threaded environment leads to compiler throwing runtime exception i.e.; ConcurrentModificationException

Q) When to use ConcurrentHashMap ?

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

2. HashMap v/s ConcurrentHashMap

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

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 5 - ConcurrentHashMap v/s SynchronizedMap
Java 5 - ConcurrentHashMap with Read and Update operations simultaneously