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
HashMap v/s ConcurrentHashMap:
|HashMap is not synchronized||ConcurrentHashMap 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 key||NULL 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 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|
|This is introduced in original collection framework in Java 1.2 version||This 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|
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
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
HashMap v/s ConcurrentHashMap
- there is always a catch between performance and thread-safety
- Choose wisely for your requirement
Happy Coding !!
Happy Learning !!