Read Also : Difference between Arraylist and Vector : Java Collections Interview Question
HashMap vs ConcurrentHashMap
1. Thread -Safe :
ConcurrentHashMap is thread-safe that is the code can be accessed by a single thread at a time.While HashMap is not thread-safe.
2. Synchronization Method:
HashMap can be synchronized by using synchronizedMap(HashMap) method. By using this method, we get a HashMap object which is almost equivalent to the Hashtable object. So every modification is performed on Map is locked on Map object.
import java.util.*; public class HashMapSynchronization { public static void main(String[] args) { // create map Map<String,String> map = new HashMap<String,String>(); // populate the map map.put("1","ALIVE "); map.put("2","IS"); map.put("3","AWESOME"); // create a synchronized map Map<String,String> syncMap = Collections.synchronizedMap(map); System.out.println("Synchronized map :"+syncMap); } }
Output:
Synchronized map :{1=ALIVE , 2=IS, 3=AWESOME}
ConcurrentHashMap synchronizes or locks on a certain portion of the Map. To optimize the performance of ConcurrentHashMap, Map is divided into different partitions depending upon the Concurrency level. So that we do not need to synchronize the whole Map Object.
3. Null keys and Null values
ConcurrentHashMap does not allow even a single null key and a null value. So the key and the value both can not be null in ConcurrentHashMap. If you try to add a null key or a null value in the ConcurrentHashMap then it will throw NullPointerException.
While in HashMap, it allows a maximum of one null key and any number of null values.
4. Performance
In a multi-threaded environment, ConcurrentHashMap is more scalable and usually faster than synchronizedHashMap. In a single-threaded environment, HashMap performs slightly better than ConcurrentHashMap.
5. Introduction to Java
HashMap is added to the Java collections framework in Java2(JDK 1.2). On the other hand, ConcurrentHashMap is introduced in Java5(JDK 1.5).
6. Fail-fast and fail-safe
The iterators returned by ConcurrentHashMap are fail-safe in nature whereas the iterators returned by HashMap are fail-fast in nature. You can find the difference between fail-fast and fail-safe in detail here.
7. When to use ConcurrentHashMap over HashMap
ConcurrentHashMap is synchronized hence it is best suited for a concurrent multi-threaded environment. HashMap is not synchronized hence it is best suited for a single-threaded environment.
Recap : Difference between HashMap and ConcurrentHashMap
HashMap | ConcurrentHashMap | |
---|---|---|
Thread-safe | No | Yes |
Synchronized | No | Yes |
Null keys and Null values | One null key, any number of null values | No null keys and no null values |
Performance | Perform better in single-threaded applications | Perform better in concurrent multi-threaded applications |
Nature of Iterator | Fail-fast | Fail-safe |
Introduction to Java | Java 2(1.2) | Java 5(1.5) |
Please write in comments in case if you have any doubts.