What causes a ConcurrentModificationException, and how can you prevent it?

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

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.

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.

Last updated: 16 July 2026

Previous question: You are working on a high-performance financial trading application that frequently updates prices and sorts them. Which Java collections would you use and why?

Next question: Why do we use builder design pattern rather than constructor-based object creation?

More Core Java - Level IV (Advanced) interview questions

All Core Java - Level IV (Advanced) questions