Sobes.tech
Senior

Почему CopyOnWriteArrayList не бросает ConcurrentModificationException при модификации во время итерации?

sobes.tech AI

Answer from AI

CopyOnWriteArrayList does not throw ConcurrentModificationException during modification while iterating because its iterators work on a snapshot of the array, which was current at the time of the iterator's creation.

Unlike regular collections, where the iterator tracks structural modifications and throws an exception upon detection, CopyOnWriteArrayList creates a new copied array with changes upon each modification. The iterator continues to work with the immutable array that was present at its creation.

This ensures:

  • Safe iteration without ConcurrentModificationException.
  • The iterator sees a consistent state of the collection at the start of iteration.

However, it is important to consider that:

  • Modifications (add, remove, etc.) are costly due to array copying.
  • The iterator does not reflect changes made after its creation.

Example:

CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();
list.add("A");
list.add("B");

for (String s : list) {
    System.out.println(s);
    list.add("C"); // will not cause ConcurrentModificationException
}

In this example, the iterator will not see the added "C" during iteration.

Почему CopyOnWriteArrayList не бросает… - sobes.tech