ConcurrentModificationException in Java – Cause and Fix with Examples

Have you ever tried removing elements from an ArrayList (or any collection) while iterating over it?

If yes, you might have encountered a ConcurrentModificationException at runtime.

This usually happens when we try to modify a collection while iterating over it using a loop.








What Does the Exception Mean?

As per Java documentation:

This exception is thrown when a collection is modified while it is being iterated, in a way that is not allowed.


Problem Example

Let’s understand this with a simple example:

List<String> values = new ArrayList<>();
values.add("A");
values.add("b-");
values.add("c");
values.add("D-");

for (String value : values) {
if (value.endsWith("-")) {
values.remove(value);
}
}

What’s Going Wrong?

In the above code:

  • We are iterating over the list
  • At the same time, we are removing elements from it

When the first matching element is removed:

  • The list size changes
  • The iterator (used internally by the for-each loop) becomes inconsistent

👉 This leads to ConcurrentModificationException


Correct Approach (Java 8+)

To safely remove elements while iterating, use removeIf():

values.removeIf(value -> value.endsWith("-"));
System.out.println("Values are: " + values);

Why removeIf() Works

  • It internally uses an iterator
  • Handles removal safely without breaking iteration
  • Cleaner and more readable

Alternative (Pre-Java 8)

If you’re not using Java 8, use an explicit iterator:

Iterator<String> iterator = values.iterator();

while (iterator.hasNext()) {
String value = iterator.next();
if (value.endsWith("-")) {
iterator.remove();
}
}

Key Takeaways

  • Don’t modify a collection directly inside a for-each loop
  • Use removeIf() in Java 8+
  • Or use Iterator.remove() for safe removal
  • ConcurrentModificationException is about unsafe modification during iteration, not multithreading

Post a Comment

0 Comments