Middle
How can you get a ConcurrentModificationException in a single-threaded program when working with a collection?
sobes.tech AI
Answer from AI
// Example code that causes ConcurrentModificationException in a single-threaded application
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ConcModExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String element = iterator.next();
if (element.equals("B")) {
// Attempting to modify the collection directly during iteration,
// performed with the iterator.
// This causes a ConcurrentModificationException.
list.remove(element);
}
}
}
}
ConcurrentModificationException can occur in a single-threaded program when attempting to modify a collection during iteration with an iterator created before the modification. Iterators in Java collection structures (such as ArrayList, HashSet, HashMap) use a so-called "fail-fast" mechanism.
The fact of the exception occurring is explained as follows:
- When the iterator is created, the collection records its internal modification count (
modCount). - Each time the iterator's methods (
next(),hasNext(),remove()) are called, a check is performed to see if the current modification count matches the one at creation. - If the count has changed since the iterator was created, a
ConcurrentModificationExceptionis thrown. This indicates that the collection was modified by another means (e.g., directly callingadd(),remove()on the collection itself) during active iteration.
The exception points to a potential data consistency problem during iteration and serves to prevent unpredictable program behavior. To avoid this, modifications to the collection during iteration should only be made through the iterator's own methods (iterator.remove()), if supported by the collection.