In this article, we will discuss various possibilities when ConcurrentModificationException is thrown and its resolution with respect to HashMap
Often, this term is quite confusing. So, we will understand each one in detailed step with example & explanation
It is one of the favorite Java interview question among interviewer
Before moving forward, we will understand few things in QnA format
Q) When does ConcurrentModificationException is thrown ?
- If 2 different threads perform operations on same HashMap object simultaneously/concurrently, then JVM throws ConcurrentModificationException
- Or try removing an entry from HashMap while iterating using for-loop or enhanced forEach loop
Q) How ConcurrentModificationException can be handled ?
- If we want to remove an entry while iterating, then obtain Iterator and then iterate through HashMap which helps to remove an entry from HashMap safely using remove() method
- Or else, go for concurrent collection introduced in Java 1.5 version like ConcurrentHashMap instead of HashMap which works on different locking strategies
- Or use removeIf() method introduced in Java 1.8 version
Note:
- We can always remove a single entry using remove() method without iterating
- Also, deleting all entries from HashMap using clear() method is very much possible
Here, we will cover 3 examples to showcase,
- How ConcurrentModificationException is thrown while iterating Map & simultaneously removing an entry using enhanced forEach loop
- Fixing ConcurrentModificationException by using Iterator to iterate Map & simultaneously removing an entry
- Iterating Map & simultaneously removing an entry using ConcurrentHashMap
1. ConcurrentModificationException is thrown while iterating & removing:
CMEThrownWhileIteratingAndRemovingMap.java
package in.bench.resources.cme.examples;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;
public class CMEThrownWhileIteratingAndRemovingMap {
public static void main(String[] args) {
// create HashMap
HashMap<Integer, String> map = new HashMap<Integer, String>();
// put few items
map.put(1, "Google");
map.put(2, "Microsoft");
map.put(3, "Oracle");
map.put(4, "Apple");
map.put(5, "Facebook");
// getting entrySet() into Set
Set<Entry<Integer, String>> entrySet = map.entrySet();
// iterate and remove items simultaneously
for(Entry<Integer, String> entry : entrySet) {
int key = entry.getKey();
if(key == 4) {
// try to remove, while iterating
map.remove(key);
}
else {
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
}
}
}
Output:
1 Google
2 Microsoft
3 Oracle
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
at java.util.HashMap$EntryIterator.next(HashMap.java:1463)
at java.util.HashMap$EntryIterator.next(HashMap.java:1461)
at in.bench.resources.cme.examples.CMEThrownWhileIteratingAndRemovingMap
.main(CMEThrownWhileIteratingAndRemovingMap.java:25)
2. Fixing ConcurrentModificationException by using Iterator for iterating and removing an entry:
FixCMEUsingIterator.java
package in.bench.resources.cme.examples;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
public class FixCMEUsingIterator {
public static void main(String[] args) {
// create HashMap
HashMap<Integer, String> map = new HashMap<Integer, String>();
// put few items
map.put(1, "Google");
map.put(2, "Microsoft");
map.put(3, "Oracle");
map.put(4, "Apple");
map.put(5, "Facebook");
// getting entrySet() into Set
Set<Entry<Integer, String>> entrySet = map.entrySet();
// Collection Iterator
Iterator<Entry<Integer, String>> itr = entrySet.iterator();
// iterate and remove items simultaneously
while(itr.hasNext()) {
Entry<Integer, String> entry = itr.next();
int key = entry.getKey();
if(key == 4) {
// try to remove, while iterating
itr.remove();
System.out.println("4th item safely removed using Iterator");
}
else {
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
}
}
}
Output:
1 Google
2 Microsoft
3 Oracle
4th item safely removed using Iterator
5 Facebook
3. Fixing ConcurrentModificationException by using ConcurrentHashMap:
- Example: ConcurrentHashMap with Read and Update operations simultaneously
- Difference between ConcurrentHashMap v/s HashMap
In the following article, we will cover how easily an entry can be removed using Java 8 APIs
Hope, you found this article very helpful. If you have any suggestion or want to contribute any other way or tricky situation you faced during Interview hours, then share with us. We will include that code here
Related Articles:
- Java – How to get all keys of a HashMap ?
- Java – How to get all values of a HashMap ?
- Java – How to get all Entries or Key-Value pairs of HashMap ?
- Java – How to get size or length of HashMap ?
- Java – How to check whether a particular key is present in HashMap ?
- Java – How to check whether a particular value is present in HashMap ?
- Java – How to check whether HashMap is empty or not ?.
- Java – Adding one HashMap to another HashMap using putAll method
- Java – How to delete an entry of HashMap ?
- Java – How to delete all entries of HashMap ?
- Java – Various ways to iterate through HashMap
- Java – To reverse order the LinkedHashMap contents
- Java – How ConcurrentModificationException can be handled
- Java 8 – How to remove an entry from HashMap by comparing values
- Java 8 – How to remove an entry from HashMap by comparing keys
Happy Coding !!
Happy Learning !!