Map: How ConcurrentModificationException can be handled in Java

In this article, we will discuss various possibilities for ConcurrentModificationException 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 amongst interviewer

 

Before moving forward, we will understand few things in QnA format

When does ConcurrentModificationException is thrown ?

  • If 2 different threads perform operations on same HashMap object simultaneously, then JVM throws ConcurrentModificationException
  • Or try removing an entry from HashMap while iterating using for-loop or enhanced forEach loop

 

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:

 

Here, we will cover 3 examples to showcase,

  1. How ConcurrentModificationException is thrown while iterating Map & simultaneously removing an entry using enhanced forEach loop
  2. Fixing ConcurrentModificationException by using Iterator to iterate Map & simultaneously removing an entry
  3. Iterating Map & simultaneously removing an entry using ConcurrentHashMap

 

Example 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)

 

Example 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

 

Example 3: fixing ConcurrentModificationException by using ConcurrentHashMap

 

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

 

Happy Coding !!
Happy Learning !!

How to remove an entry from HashMap in Java 8
Java: Sorting after merging two String Array