Difference between HashMap and ConcurrentHashMap
Carvia Tech | 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:
HashMap is part of traditional
java.util package, while ConcurrentHashMap is part of
HashMap implementation is not synchronized, hence not thread-safe in nature, while ConcurrentHashMap is thread-safe.
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.
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:
- Difference between HashMap, LinkedHashMap and TreeMap
- What is difference between HashMap and HashSet
- Discuss internals of a ConcurrentHashmap (CHM) in Java
- What is difference between Vector and ArrayList, which one shall be preferred
- Difference between Callable and Runnable Interface
- Difference between JDK JRE and JVM
- Can the keys in HashMap be mutable