What is ConcurrentModificationException in Java?

“The ConcurrentModificationException occurs when a resource is modified while not having the privileges of modification.”
In other words, The Java ConcurrentModificationException (as the name suggests) occurs due to the concurrency problem. It is assumed that you have prior knowledge of threads and multi-threading before proceeding. Some classes in Java, like Collection classes, do not allow a thread to modify an element while another thread is iterating over it. If the modification operation (add, remove etc) is performed, the program throws ConcurrentModificationException. This is not the only case for this exception to occur. However, digging deeper will go out of the scope of this article.

Example

Let’s look at an example of how this exception occurs.

import java.util.List;
import java.util.Iterator;
import java.util.ArrayList;

//Test driver for ConcurrentModificationException
public class ConcurrentModificationExceptionTestDriver1 {

	public static void main(String[] args) {
		List<String> businessDays = new ArrayList<>();

		businessDays.add("Monday");
		businessDays.add("Tuesday");
		businessDays.add("Wednesday");
		businessDays.add("Thursday");
		businessDays.add("Friday");
		businessDays.add("Saturday");
		businessDays.add("Sunday");

		Iterator<String> iterator = businessDays.iterator();
		while (iterator.hasNext()) {
			String day = iterator.next();
			if (day.equals("Sunday")) {
				// removing a list item while iterating
				// leading to java.util.ConcurrentModificationException
				businessDays.remove(day);
			}
		}
	}
}

Output

Exception in thread "main" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1042) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:996) at milestone.thirty.seven.ConcurrentModificationExceptionTestDriver1.main(ConcurrentModificationExceptionTestDriver1.java:22)

How to Avoid ConcurrentModificationException in Java?

There are different workarounds for the ConcurrentModificationException. Here are enlisted a few. You can opt for anyone as per your needs.
  1. Avoid modification while iteration.
  2. Use traditional loops for simultaneous iteration and modification.
  3. Create a copy of values to be modified while using iterators. Update the values once the iteration is over.

Example

Here’s an example of how you can avoid the ConcurrentModificationException.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

//Test driver for ConcurrentModificationException
public class ConcurrentModificationExceptionTestDriver2 {

	public static void main(String[] args) {

		List<String> businessDays = new ArrayList<>();

		businessDays.add("Monday");
		businessDays.add("Tuesday");
		businessDays.add("Wednesday");
		businessDays.add("Thursday");
		businessDays.add("Friday");
		businessDays.add("Saturday");
		businessDays.add("Sunday");
		
		System.out.println("Initial Business Days: " + businessDays);

		// Method II - Using traditional for loop
		for (int i = 0; i < businessDays.size(); i++) {
			if (businessDays.get(i).equals("Sunday")) {
				businessDays.remove(i);
			}
		}
		
		Iterator<String> iterator = businessDays.iterator();
		List<String> businessDaysToBeRemoved = new ArrayList<>();

		// Method III - Creating a copy of elements 
		while (iterator.hasNext()) {
			String day = iterator.next();
			if (day.equals("Saturday")) {
				// Add values to be removed in the list
				businessDaysToBeRemoved.add(day);
			}
		}	
		businessDays.removeAll(businessDaysToBeRemoved);
		System.out.println("Final Business Days: " + businessDays);
	}
}

Output

Initial Business Days: [Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday] Final Business Days: [Monday, Tuesday, Wednesday, Thursday, Friday]
ConcurrentModificationException in Java - 1

Conclusion

That was a quick dose of dealing with the ConcurrentModificationException in Java. Feel free to hop on whenever you feel stuck. Like always, the key to moving forward is practice and patience. Till then, keep learning and keep growing.