CodexBloom - Programming Q&A Platform

Issues with ConcurrentModificationException in Java with ExecutorService and ArrayList

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-08-28
java concurrency executor-service arraylist Java

I recently switched to This might be a silly question, but I'm experiencing a `ConcurrentModificationException` when trying to manipulate an `ArrayList` in a multi-threaded environment using `ExecutorService`... The idea is to have multiple threads processing elements from the list, but I'm encountering this exception intermittently. Here's a simplified version of my code: ```java import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ConcurrentModificationExample { private List<Integer> numbers = new ArrayList<>(); public ConcurrentModificationExample() { for (int i = 0; i < 10; i++) { numbers.add(i); } } public void processNumbers() { ExecutorService executor = Executors.newFixedThreadPool(5); for (int i = 0; i < numbers.size(); i++) { final int index = i; executor.submit(() -> { // Simulate some processing int num = numbers.get(index); System.out.println("Processing: " + num); // Attempt to remove a number during processing if (num % 2 == 0) { numbers.remove(index); } }); } executor.shutdown(); } public static void main(String[] args) { ConcurrentModificationExample example = new ConcurrentModificationExample(); example.processNumbers(); } } ``` In the snippet above, I'm trying to remove even numbers while processing them in separate threads. However, this leads to a `ConcurrentModificationException`, which I suspect is due to the fact that I'm modifying the list while iterating over it. I've tried using `CopyOnWriteArrayList`, but that seems to have performance issues due to the frequent writes. Is there a better way to safely modify the list while processing it in parallel, or should I rethink my approach? Any suggestions on best practices to avoid this issue would also be appreciated. How would you solve this? I'm coming from a different tech stack and learning Java. What am I doing wrong?