Difference between HashMap and ConcurrentHashMap

Carvia Tech | May 25, 2019 | 1 min read | 41 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. What is difference between HashMap and HashSet
  2. Discuss internals of a ConcurrentHashmap (CHM) in Java
  3. Difference between Implementing Runnable and Extending Thread
  4. What is difference between Vector and ArrayList, which one shall be preferred
  5. Can the keys in HashMap be mutable
  6. Difference between Comparable and Comparator in Java
  7. What is difference between JDK JRE and JVM



Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 month ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info