ConcurrentModificationException in Java with Examples
Last Updated :
02 Apr, 2020
Improve
ConcurrentModificationException in Multi threaded environment
In multi threaded environment, if during the detection of the resource, any method finds that there is a concurrent modification of that object which is not permissible, then this ConcurrentModificationException might be thrown.
Java
Java
- If this exception is detected, then the results of the iteration are undefined.
- Generally, some iterator implementations choose to throw this exception as soon as it is encountered, called fail-fast iterators.
// Java program to show
// ConcurrentModificationException
import java.util.Iterator;
import java.util.ArrayList;
public class modificationError {
public static void main(String args[])
{
// Creating an object of ArrayList Object
ArrayList<String> arr
= new ArrayList<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
arr.add("Four");
try {
// Printing the elements
System.out.println(
"ArrayList: ");
Iterator<String> iter
= arr.iterator();
while (iter.hasNext()) {
System.out.print(iter.next()
+ ", ");
// ConcurrentModificationException
// is raised here as an element
// is added during the iteration
System.out.println(
"\n\nTrying to add"
+ " an element in "
+ "between iteration\n");
arr.add("Five");
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output:
How to avoid ConcurrentModificationException?
To avoid this exception,
ArrayList: One, Trying to add an element in between iteration java.util.ConcurrentModificationException
- Simply we can do the modifications once the iteration is done, or
- Implement the concept of the synchronized block or method
// Java program to show
// ConcurrentModificationException
import java.util.Iterator;
import java.util.ArrayList;
public class modificationError {
public static void main(String args[])
{
// Creating an object of ArrayList Object
ArrayList<String> arr
= new ArrayList<String>();
arr.add("One");
arr.add("Two");
arr.add("Three");
arr.add("Four");
try {
// Printing the elements
System.out.println(
"ArrayList: ");
Iterator<String> iter
= arr.iterator();
while (iter.hasNext()) {
System.out.print(iter.next()
+ ", ");
}
// No exception is raised as
// a modification is done
// after the iteration
System.out.println(
"\n\nTrying to add"
+ " an element in "
+ "between iteration: "
+ arr.add("Five"));
// Printing the elements
System.out.println(
"\nUpdated ArrayList: ");
iter = arr.iterator();
while (iter.hasNext()) {
System.out.print(iter.next()
+ ", ");
}
}
catch (Exception e) {
System.out.println(e);
}
}
}
Output:
From the output, it can be seen clearly that with minimal changes in the code, ConcurrentModificationException can be eliminated.
ArrayList: One, Two, Three, Four, Trying to add an element in between iteration: true Updated ArrayList: One, Two, Three, Four, Five,