Sobes.tech
Junior — Middle

What does the occurrence of a ConcurrentModificationException in Java mean, and in what situations can it be thrown?

sobes.tech AI

Answer from AI

The ConcurrentModificationException in Java occurs when the collection is structurally modified (e.g., adding or removing elements) during iteration, without using the iterator's own methods. This is a fail-fast mechanism to prevent unpredictable behavior.

Typical situations where this exception is thrown:

  • Iterating over an ArrayList with an iterator, and calling list.remove() directly instead of iterator.remove().
  • Modifying a collection from another thread during iteration without synchronization.

Example:

List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
for (String s : list) {
    if (s.equals("b")) {
        list.remove(s); // will throw ConcurrentModificationException
    }
}

The correct way to remove elements during iteration:

Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
    String s = iterator.next();
    if (s.equals("b")) {
        iterator.remove(); // safe
    }
}