What is ConcurrentModificationException in Java?
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.- Avoid modification while iteration.
- Use traditional loops for simultaneous iteration and modification.
- 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]