Difference between HashMap and ConcurrentHashMap in Java

Introduction

HashMap is a class which is available under traditional Collection and ConcurrentHashMap is a class which is added later under Concurrent Collections. ConcurrentHashMap is a collection in Java is introduced as an alternate of Hashtable, which is a synchronized collection class.

The main difference between HashMap and ConcurrentHashMap is that the HashMap is non-synchronized, non-thread safe and not for use in Concurrent multi-threaded environment while ConcurrentHashMap is a thread-safe collection and is intended to be used as primary Map implementation especially for multi-threaded and Concurrent environment. Apart from thread-safety, there are some subtle differences between HashMap and ConcurrentHashMap which we will see in this article.

HashMap Vs ConcurrentHashMap

Here will see some more details about HashMap and ConcurrentHashMap and compare them on various parameters like thread-safety, synchronization, performance, ease of use etc.

  1. As mentioned above the major difference is that Concurrent HashMap is thread-safe and can be used in a concurrent environment without external synchronization. It doesn’t provide the same level of synchronization as achieved by using Hashtable but it’s enough for the most practical purpose.
  2. HashMap allows synchronization by wrapping it using Collections.synchornizedMap(HashMap) and it will return a collection which is almost equal to Hashtable, where every modification operation on Map is locked on Map object. In case of ConcurrentHashMap, thread-safety is achieved by dividing whole Map into different partition based upon Concurrency level and only locking particular part instead of locking the whole Map.
  3. Concurrent HashMap is more scalable and performs better than Synchronized HashMap in the multi-threaded environment while in Single threaded environment both collections gives comparable performance, where HashMap is slightly better.

If we summarize the difference between both the collection, it turns out ConcurrentHashMap is a better choice than synchronized HashMap if you are using them as cache, which is the most popular use case of a Map in Java application. ConcurrentHashMap is more scalable and outperforms when read threads outnumber the number of writer threads.

Please Post Your Comments & Reviews

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.