Runtime Error
java.util.ConcurrentModificationException: null at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1034) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:954)
What This Error Means
This error occurs when a program attempts to modify a collection (like an ArrayList or HashSet) while it is being iterated over by a foreach loop, iterator, or lambda expression.
Why It Happens
This error often happens when multiple threads are accessing the same collection concurrently, or when a program is using a collection in a multithreaded environment without proper synchronization.
How to Fix It
- 1To fix this error, you can use the following solutions:
- 21. Use an Iterator to remove elements while iterating over a collection.
- 32. Create a temporary collection to store the elements to be removed.
- 43. Use a thread-safe collection, such as CopyOnWriteArrayList or ConcurrentHashMap.
- 54. Synchronize access to the collection using a lock or a semaphore.
Example Code Solution
import java.util.ArrayList;
import java.util.Iterator;
public class ConcurrencyErrorExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
for (String s : list) {
if (s.equals("B")) {
list.remove(s);
}
}
}
}import java.util.ArrayList;
import java.util.Iterator;
public class ConcurrencyErrorExample {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String s = iterator.next();
if (s.equals("B")) {
iterator.remove();
}
}
}
}Fix for java.util.ConcurrentModificationException: null at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1034) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:954)
Browse Related Clusters
Related JAVA Errors
ORA-12545: TNS:Cannot register with TSLS (TNS Listener Service)
Error executing SQL query: Cannot insert explicit value for identity c
java.lang.StackOverflowError at com.example.Main.main(Main.java:15) -
Could not initialize Bean Validation provider for the constraint annot
Related JAVA Blog Articles
Have a different error? Get an instant explanation.
Explain Another Error