A ConcurrentModificationException occurs when a collection is structurally modified while it is being traversed using an iterator, for-each loop, or similar iteration mechanism. Java's fail-fast collections detect such unexpected modifications and throw this exception to prevent inconsistent behavior during iteration.
Key Points: • The exception commonly occurs when elements are added or removed from a collection while iterating over it using a for-each loop or Iterator. • To safely remove elements during iteration, use the Iterator.remove() method instead of directly modifying the collection. • In multithreaded applications, concurrent collections such as CopyOnWriteArrayList and ConcurrentHashMap can be used to avoid this issue.
Example: Suppose you are iterating through a list of employees and directly remove an employee from the list inside a for-each loop. The collection structure changes during iteration, causing a ConcurrentModificationException.
Code Example:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<String> names =
new ArrayList<>();
names.add("John");
names.add("David");
names.add("Alice");
Iterator<String> iterator =
names.iterator();
while (iterator.hasNext()) {
String name = iterator.next();
if ("David".equals(name)) {
iterator.remove();
}
}
System.out.println(names);
}
}Interview Tip: A concise interview answer is: ConcurrentModificationException occurs when a collection is modified while it is being iterated. It can be prevented by using Iterator.remove() for safe removal during iteration or by using concurrent collections such as CopyOnWriteArrayList and ConcurrentHashMap in multithreaded environments.