During a code review, you find a ConcurrentModificationException caused by modifying a list while iterating over it in a multi-threaded environment. How would you refactor this code?

To eliminate a ConcurrentModificationException in a multi-threaded environment, the collection access must be made thread-safe. A common approach is to replace regular collections with concurrent collections such as CopyOnWriteArrayList or protect iteration and modification operations using synchronization. This ensures that one thread's changes do not interfere with another thread's traversal of the collection.

Key Points

Example

Consider a chat application where one thread displays online users while another thread adds or removes users. Using a standard ArrayList may cause ConcurrentModificationException. Switching to CopyOnWriteArrayList allows both operations to execute safely.

import java.util.concurrent.CopyOnWriteArrayList;

public class UserManager {

    public static void main(String[] args) {

        CopyOnWriteArrayList<String> users =
                new CopyOnWriteArrayList<>();

        users.add("John");
        users.add("Alice");
        users.add("David");

        for (String user : users) {

            if ("Alice".equals(user)) {
                users.remove(user);
            }

            System.out.println(user);
        }

        System.out.println(users);
    }
}

Interview Tip

A concise interview answer is: I would refactor the code by using a thread-safe collection such as CopyOnWriteArrayList or by synchronizing access to the collection. This prevents ConcurrentModificationException and ensures safe iteration and modification when multiple threads access the same list.

Last updated: 16 July 2026

Previous question: You are developing an application that loads plugins from third-party sources. How would you ensure system security while using these plugins?

Next question: Your application leaks memory because cache objects are handled badly. How would you fix memory management?

More Core Java - Level V (Expert) interview questions

All Core Java - Level V (Expert) questions