Difference between HashMap and ConcurrentHashMap in Java Collection


ConcurrentHashMap is introduced as an alternative of Hashtable in Java 1.5 version, ConcurrentHashMap is a synchronized collection class, And the main difference between HashMap and ConcurrentHashMap is HashMap is not synchronized as well as not thread safe because of that not use in Concurrent multi-threaded environment. But ConcurrentHashMap is a thread-safe collection class and we can use them in Concurrent multi-threaded environment.

 


Difference between HashMap and ConcurrentHashMap classes  in Java are following:-

 

Synchronized HashMap is not synchronized but HashMap can be synchronized using the Collections.synchronizedMap() method ConcurrentHashMap is synchronized.
Thread Safety HashMap is not thread safe. ConcurrentHashMap is thread safe and fit for use in a multi-threaded environment
Iterator type HashMap iterator is fail-fast as it throws a ConcurrentModificationException  if concurrent modification happens during iteration. ConcurrentHashMap is fail-safe and it will never throw ConcurrentModificationException during iteration.
Null values HashMap allows one key and value to be null. ConcurrentHashMap does not allow null key/value. It will throw NullPointerException.
Performance HashMap is faster because there is no synchronization ConcurrentHashMap is slower than HashMap.
Introduce HashMap is a part of Java’s collection since Java 1.2 ConcurrentHashMap is a part of Java collection since Java 1.5
   

 


 

Leave a Reply

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