We have learned about HashMap and ConcurrentHashMap in java. Both are the most popular concepts of Java. But HashMpa was introduced in JDK 1.2 and ConcurrentHashMap introduced in 1.5. So it is the most common question for an interview What is the difference between hashmap and Concurrenthashmap? and What is the need of Concurrenthashmap in java?
Difference between hashmap and Concurrenthashmap
1. HashMap introduced in Java 1.2 version and it is under Traditional Collection.
ConcurrentHashMap introduced in 1.5 version and it is under Concurrent Collections.
2. HashMap is not threaded safe by default because it is non-Synchronized in nature. We can make it thread-safe by using the synchronized keyword. ConcurrentHashMap is Thread-safe in nature. Here we don’t need to use any keyword for synchronization.
3. For a single thread performance of HashMap is relatively high because it is non-synchronized in nature. But in the case of multithreaded, it has less performance than ConcurrentHashMap. Because multiple threads can’t perform the operation at the same time.
In the case of multiple threads, the ConcurrentHashMap performance is high because multiple threads can perform the operation on it or per segment.
4. The HashMap throws ConcurrentModificationException if we modify it while traversing it.
But the ConcurrentHashMap won’t get any exception while performing any modification at the time of Iteration.
5. HashMap allows null as a key and value. ConcurrentHashMap doesn’t allow null as a key and value.
6. A HashMap can be synchronized externally by using Collections.synchronizedMap() method. The object locks the whole HashMap and all the operations will be synchronized. That makes it slower as compare to ConcurrentHashMap.
The ConcurrentHashMap is synchronized by default and one thread locks only a segment of ConcurrentHashMap. The modifying operations like add and delete are synchronized but the read operations are not synchronized. So it performs better than HashMap.