Java – How ConcurrentModificationException can be handled ?

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 ?

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

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:

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:

Happy Coding !!
Happy Learning !!

Java 8 - How to remove an entry from HashMap by comparing values ?
Java - Merging two String[] Array and Sorting