megan847
megan847 Mar 7, 2026 β€’ 0 views

How to fix ConcurrentModificationException when iterating through ArrayLists in Java

Hey everyone! πŸ‘‹ Ever run into that super annoying `ConcurrentModificationException` when you're trying to loop through an ArrayList in Java? 😫 It's like, you're just trying to add or remove something, and BAM! Error. I'm hoping to get a good explanation to help me understand it once and for all!
πŸ’» Computer Science & Technology
πŸͺ„

πŸš€ Can't Find Your Exact Topic?

Let our AI Worksheet Generator create custom study notes, online quizzes, and printable PDFs in seconds. 100% Free!

✨ Generate Custom Content

1 Answers

βœ… Best Answer
User Avatar
jennifer910 Dec 31, 2025

πŸ“š Understanding ConcurrentModificationException

The ConcurrentModificationException in Java arises when you try to modify a collection (like an ArrayList) while you're actively iterating over it using a standard iterator. This typically happens when multiple threads are accessing and modifying the same list concurrently, but it can also occur in single-threaded scenarios if you're not careful.

πŸ“œ Historical Context

This exception was introduced to provide fail-fast behavior for iterators. Before its introduction, modifications during iteration could lead to unpredictable behavior and data corruption. The exception helps developers catch these issues early on.

πŸ”‘ Key Principles

  • πŸ” Fail-Fast Iterators: Java's iterators are designed to be fail-fast, meaning they immediately throw a ConcurrentModificationException if they detect that the collection has been structurally modified during iteration (except through the iterator's own remove() or add() methods).
  • 🧡 Multithreading Issues: The most common cause is concurrent modification from multiple threads. Without proper synchronization, one thread might be iterating while another modifies the list.
  • ☝️ Single-Threaded Issues: It can also happen in a single thread if you modify the list directly within a loop using the remove() or add() methods of the ArrayList itself, rather than the iterator.

πŸ› οΈ Ways to Fix ConcurrentModificationException

  • πŸ”’ Use Synchronization: When dealing with multiple threads, use synchronization mechanisms like synchronized blocks or ReentrantLock to ensure only one thread modifies the list at a time.
  • πŸ’‘ Use Concurrent Collections: Employ concurrent collection classes from the java.util.concurrent package, such as CopyOnWriteArrayList or ConcurrentHashMap. These are designed for concurrent access and modification.
  • πŸ”ͺ Use Iterator's remove() Method: Always use the iterator's remove() method to remove elements during iteration. Never use the ArrayList's remove() method directly.
  • πŸ“ Collect Modifications: Instead of modifying the list during iteration, collect the elements to be removed or added in a separate list, and then perform the modifications after the iteration is complete.
  • ➑️ Use ListIterator: When you need to add elements during iteration, you can use ListIterator which provides add() and remove() methods that handle concurrent modification safely within a single thread.

πŸ’» Real-world Examples

Example 1: Using Iterator's remove()


import java.util.ArrayList;
import java.util.Iterator;

public class IteratorRemoveExample {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Cherry");

        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            if (element.equals("Banana")) {
                iterator.remove(); // Correct way to remove
            }
        }

        System.out.println(list); // Output: [Apple, Cherry]
    }
}

Example 2: Using CopyOnWriteArrayList (Concurrency)


import java.util.concurrent.CopyOnWriteArrayList;

public class CopyOnWriteExample {
    public static void main(String[] args) throws InterruptedException {
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
        list.add("Apple");

        Thread t1 = new Thread(() -> {
            for (String s : list) {
                System.out.println("Thread 1: " + s);
                try { Thread.sleep(100); } catch (InterruptedException e) {}
            }
        });

        Thread t2 = new Thread(() -> {
            list.add("Banana");
            list.add("Cherry");
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(list); // Output: Could be [Apple, Banana, Cherry] in some order
    }
}

βœ”οΈ Conclusion

Handling ConcurrentModificationException requires careful consideration of how you modify collections during iteration, especially in multithreaded environments. By understanding the fail-fast nature of iterators and applying appropriate techniques like using iterator's remove(), concurrent collections, or synchronization, you can effectively avoid this common Java pitfall.

Join the discussion

Please log in to post your answer.

Log In

Earn 2 Points for answering. If your answer is selected as the best, you'll get +20 Points! πŸš€