ConcurrentModificationException while using Iterator in Java
Last Updated :
21 Apr, 2021
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.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...