ConcurrentHashMap in Java

ConcurrentHashMap is an alternative to HashTable and synchronizedMap. It is used in multi threaded applications and provided better performance when compared to HashTable and synchronisedMap.

ConcurrentHashMap Implementation In Java

In concurrentHashMap we have new feature called concurrency level . The ConcurrentHashMap is divided into segments based on the concurrency level.We need to be careful while providing the concurrency level as this impacts the performance of the map. The default concurrency level is 16 which means 16 threads can access the map simultaneously when each thread is operating on a different section, the map is basically divided in 16 segments and each segment is governed with a different lock. This mechanism boosts the performance of the ConcurrentHashMap in a thread safe environment. But the update operations like put(), remove() , putAll() or clear() are not synchronized and may not reflect the most recent change in the map.

ConcurrentHashMap Example

Features in ConcurrentHashMap

  • It doesn’t not allow null key and values.
  • The iterator in ConcurrentHashMap is fail safe which means it doesn’t throw ConcurrentModificationException if the map is updated while iteration.
  • The update operations in ConcurrentHashMap are thread safe which means at a time only one thread can update a segment of the concurrentHashmap.
  • Any number of thread can perform the  read operations without locking the map.
  • Since , concurrentHashMap do not blocks only a portion of the map, there is a chance of read overlapping with the update operation.In that case the result returned by get() method will only return the recently completed operation.
  • ConcurrentHashMap is not ordered.

When to use ConcurrentHashMap

It should be used when there are more reader threads than writer threads . If writer threads are equal to reader threads are more than reader thread then the performance of ConcurrentHashMap is same as the performance of Hashtable or synchronizedMap.


I hope you liked this article.Happy Coding 🙂

Leave a comment

Your email address will not be published. Required fields are marked *