Difference between HashMap and ConcurrentHashMap

Upasana | May 25, 2019 | 1 min read | 410 views


Both HashMap (since JDK 1.2) and ConcurrentHashMap (since JDK 1.5) are hash table implementation but with different usecases in mind.

Key differences between the two:

Package

HashMap is part of traditional java.util package, while ConcurrentHashMap is part of java.util.concurrent package.

Thread-safe

HashMap implementation is not synchronized, hence not thread-safe in nature, while ConcurrentHashMap is thread-safe.

ConcurrentModificationException

The Iterator returned by HashMap are fail-fast in nature i.e. if the map is structurally modified at any time after the iterator is created, in any way except through the iterator’s own remove method, the iterator will throw a ConcurrentModificationException. On the other side, Iterator returned by ConcurrentHashMap are weakly-consistent and do not throw any ConcurrentModificationException.

Performance in multithreaded

If we synchronize HashMap, then at most one thread and read or write to HashMap, while in case of ConcurrentHashMap any number of threads can concurrently read and configurable number of threads can write to CHM.

Usecase

If only one thread is going to read and write or you already have a lock at global level, then HashMap might be the better choice. For highly concurrent environment where many threads will read or write to shared Map, ConcurrentHashMap should be preferred over HashMap.

Null values

HashMap support nulls values and null key, but ConcurrentHashMap does not allow null key or value (just like Hashtable)


Top articles in this category:
  1. Difference between HashMap, LinkedHashMap and TreeMap
  2. What is difference between HashMap and HashSet
  3. Discuss internals of a ConcurrentHashmap (CHM) in Java
  4. What is difference between Vector and ArrayList, which one shall be preferred
  5. Difference between Callable and Runnable Interface
  6. Difference between JDK JRE and JVM
  7. Can the keys in HashMap be mutable

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.