CodexBloom - Programming Q&A Platform

Java 11 - Issues with ConcurrentModificationException when Using ArrayList in Multi-threaded Environment

👀 Views: 4 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-06
java concurrency multithreading Java

I'm learning this framework and I'm following best practices but I'm stuck on something that should probably be simple... Quick question that's been bugging me - I'm facing a `ConcurrentModificationException` in my Java 11 application when accessing an `ArrayList` from multiple threads. The problematic code snippet looks like this: ```java import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ConcurrentListExample { private List<String> items = new ArrayList<>(); public void addItem(String item) { items.add(item); } public void printItems() { for (String item : items) { System.out.println(item); } } public static void main(String[] args) { ConcurrentListExample example = new ConcurrentListExample(); ExecutorService executor = Executors.newFixedThreadPool(2); executor.submit(() -> { for (int i = 0; i < 10; i++) { example.addItem("Item " + i); } }); executor.submit(() -> { for (int i = 0; i < 10; i++) { example.printItems(); } }); executor.shutdown(); } } ``` When I run the application, I occasionally get the following stack trace: ``` Exception in thread "pool-1-thread-1" java.util.ConcurrentModificationException at java.base/java.util.ArrayList$Itr.checkForComodification(ArrayList.java:1021) at java.base/java.util.ArrayList$Itr.next(ArrayList.java:900) at ConcurrentListExample.printItems(ConcurrentListExample.java:10) ``` I tried several approaches to fix this issue, like using `Collections.synchronizedList` to wrap the `ArrayList`, but that made the code more complex and didn't fully resolve the problem. I also considered switching to `CopyOnWriteArrayList`, but I'm concerned about performance implications since I'll be reading and writing frequently. What is the best practice for safely iterating over a list in a multi-threaded context while maintaining performance? Is there a recommended way to handle this without running into `ConcurrentModificationException`? My development environment is Linux. Thanks in advance! I've been using Java for about a year now. My team is using Java for this web app. I appreciate any insights!