HashMap vs ConcurrentHashMap

Posted on Updated on

ConcurrentHashMap was introduce with JDK1.5 release to replace legacy class Hashtable. In multithreaded environment ConcurrentHashMap performs better as compared to Hashtable and Synchronized Map as well. All methods of Hashtable are synchronized which makes them quite slow due to contention if a number of thread increases. While ConcurrentHashMap is specially designed for concurrent uses which by default allows 16 threads to simultaneously read and write from map without any external synchronization.

One of the most common question asked in interview is HashMap vs Hashtable. As ConcurrentHashMap is introduced to replace Hashtable, it become obvious to ask questions around HashMap and ConcurrentHashMap in interviews. Here are some differences between these two classes.

Differences between HashMap and ConcurrentHashMap.

HashMap ConcurrentHashMap
HashMap is not thread-safe. ConcurrentHashMap is thread-safe so we can use it in multithread environment.
We can use synchronizedMap(HashMap) method to syncronize HashMap which locks whole map while reading or writing. Since ConcurrentHashmap internally divided into different segments it synchronizes or locks on the certain portion of the map. So, multiple read and one write operation can perform on it simultaneously.
HashMap allows one Null value. ConcurrentHashMap doesn't allow Null value.
HashMap perform slightly better in single threaded environment as compare to ConcurrentHashMap while in case of multi-threaded environment it perform similar to Hashtable. ConcurrentHashMap performs better in multithread environment as compare to HashMap and Hashtable as it is internally divided into segments.
HashMap is fail-fast throws ConcurrentModificationException. ConcurrentHashMap is failsafe so it doesn't throws ConcurrentModificationException.

Sample example of HashMap which throws ConcurrentModificationException when we attempt to write while reading it.

Output

Now replace HashMap with ConcurrentHashMap and we will not get ConcurrentModificationException with similar code.

Output

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.