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: • CopyOnWriteArrayList allows safe iteration even when other threads modify the collection. • Synchronization can be used to ensure that iteration and updates occur in a controlled, thread-safe manner. • Choose the solution based on the application's workload—CopyOnWriteArrayList is ideal for frequent reads and infrequent writes.

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.

Code Example:

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.