ConcurrentModificationException has thrown by methods that have detected concurrent modification of an object when such modification is not permissible. If a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will throw this ConcurrentModificationException. Here we will be understanding this exception with an example of why it occurs and how changes are made simultaneously which is the root cause for this exception. In the later part, we will understand how to fix it up.
Example 1: ConcurrentModificationException
Java
import java.util.ArrayList;
import java.util.Iterator;
public class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<>();
list.add( 1 );
list.add( 2 );
list.add( 3 );
list.add( 4 );
list.add( 5 );
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer value = iterator.next();
System.out.println( "value: " + value);
if (value.equals( 2 )) {
System.out.println(
"========================" );
System.out.println( "removing value: "
+ value);
System.out.println(
"========================" );
list.remove(value);
}
}
}
}
|
Output:

Output Explanation:
ConcurrentModificationException is thrown when the next() method is called as the iterator is iterating the List, and we are making modifications in it simultaneously. Now in order to avoid this exception so let us do discuss a way out of using iterator directly which is as follows:
Example 2: Resolving ConcurrentModificationException
Java
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList<>();
list.add( 1 );
list.add( 2 );
list.add( 3 );
list.add( 4 );
list.add( 5 );
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
Integer value = iterator.next();
System.out.println( "value: " + value);
if (value.equals( 2 )) {
System.out.println(
"========================" );
System.out.println( "removing value: "
+ value);
System.out.println(
"========================" );
iterator.remove();
}
}
}
}
|
Output:

Output Explanation:
ConcurrentModificationException is not thrown because the remove() method does not cause a ConcurrentModificationException.
Feeling lost in the vast world of Backend Development? It's time for a change! Join our
Java Backend Development - Live Course and embark on an exciting journey to master backend development efficiently and on schedule.
What We Offer:
- Comprehensive Course
- Expert Guidance for Efficient Learning
- Hands-on Experience with Real-world Projects
- Proven Track Record with 100,000+ Successful Geeks
Last Updated :
21 Apr, 2021
Like Article
Save Article