Java Collection Interview Questions
Comparing HashMap and ConcurrentHashMap in Java
Know the differences between the most widely used collection classes.

In the last article, I have explained the internal working mechanism of the hashMap and everything you may be asked in the interviews. Now, this is another interesting question that is generally asked in interviews → What are the differences between HashMap and CocurrentHashMap?
Through the medium of this article, we’ll see how these are different and their working mechanism.
Before we jump into this topic I would recommend you go through the below article which will clear your concepts related to HashMap and its internal working mechanism. This article is a continuation of the last article.
What is HashMap?
- Basically,
HashMapis one of the most popular Collection classes in the Java collection framework.HashMapinternally usesHashTableimplementation. ThisHashMapclass extendsAbstractMapclass that implements theMapinterface. HashMapstores the entries in the form of a key-value pair and allows at max one null key and multiple null values.- Java
HashMapis not thread-safe and hence it should not be used in multithreaded applications. For the multi-threaded applications, we should useConcurrentHashMapclass.
What is ConcurrentHashMap?
- Java
ConcurrentHashMapclass is part of the Collection classes in the Java collection framework.
Basically, it is a HashTable implementation, that supports concurrent retrieval and updates in the map.
- Hence it can be used in multi-threaded applications to avoid
ConcurrentModificationException. - While iterating over a hashmap using an iterator, if we try to modify the structure of the map(i.e. the number of entries (either remove or put a new entry in the map)), then we get
ConcurrentModificationException. To get rid of this exception and to change the structure of the map we should useConcurrentHashMap. - The
ConcurrentHashMapoperations are thread-safe.
ConcurrentHashMapdoesn’t allownullfor keys and values. If we try to add null key or value it throwsNullPointerException.
The ConcurrentHashMap class is similar to HashMap, except it’s thread-safe and allows modification while iterating over it.
What Is the Issue With HashMap While Iterating Over It?
Let’s see a program to understand this.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ExceptionExample {
public static void main(String[] args) {
Map<String, Long> phoneBook = new HashMap<String, Long>();
phoneBook.put("Vikram",8149101254L);
phoneBook.put("Mike",9020341211L);
phoneBook.put("Jim",7788111284L);
Iterator<String> keyIterator = phoneBook.keySet().iterator();
while (keyIterator.hasNext()){
String key = keyIterator.next();
if ("Vikram".equals(key)){
phoneBook.put("John",9220341211L);
}
}
}
}Output:
Exception in thread “main” java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1445)
at java.util.HashMap$KeyIterator.next(HashMap.java:1469)
at ExceptionExample.main(ExceptionExample.java:16)- When a new entry is inserted into the HashMap, the Iterator for the keys fails. The Iterator on Collection objects is
fail-fasti.e. any modification in the structure or the number of entries in the collection object(here map object) will trigger this exception. - Hence the exception
ConcurrentModificationExceptionis thrown. Basically,HashMapcontains a variable to count the number of modifications and the iterator uses it when you call its next() function to get the next entry.
The above scenario can be overcome using ConcurrentHashMap and hence it’s advised not to use hashmap where the structure of the map is modified.
What if the Existing Key-Value Pair Is Updated and No New Entry Is Added to the Map? Will It Throw an Exception?
In the above program, inside the if condition, if we update an existing key-value pair using the put method as shown below:
phoneBook.put("Vikram", "8149001100");
In this case, there won’t be any exception because the map is modified but the map’s structure remains the same(i.e. the number of entries in the map).
Now Let’s Try With ConcurrentHashMap:
Let’s use the ConcurrentHashMap instead of HashMap and see if this resolves our exception issue or not. Below piece of code below uses ConcurrentHashMap in place of HashMap.
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ExceptionExample {
public static void main(String[] args) {
Map<String, Long> phoneBook = new ConcurrentHashMap<String, Long>();
phoneBook.put("Vikram", 8149101254L);
phoneBook.put("Mike", 9020341211L);
phoneBook.put("Jim", 7788111284L);
Iterator<String> keyIterator = phoneBook.keySet().iterator();
System.out.println("Map Content before modification : " + phoneBook);
while (keyIterator.hasNext()) {
String key = keyIterator.next();
if ("Vikram".equals(key)) {
phoneBook.put("John", 9220341211L);
}
}
System.out.println("Map Content after modification : " + phoneBook);
}
}Output:
Map Content before modification : {Mike=9020341211, Vikram=8149101254, Jim=7788111284}
Map Content after modification : {Mike=9020341211, John=9220341211, Vikram=8149101254, Jim=7788111284}On line number 18, we have added a new entry in the map same as the previous example while iterating over the map. But this time we don’t see an exception in the output.
The reason behind this is, that the iterator and the map both are backing each other so that they keep track of changes in one another.
That’s all for this article. Hope you enjoyed it.






