Course contentsShow
← Java
Lesson 1306 of 2,87029. Iterators and IterableFree lesson

CopyOnWriteArrayList: A Fail-Safe Example

Explore CopyOnWriteArrayList's iterator that never throws exceptions because it iterates over an immutable snapshot.

CopyOnWriteArrayList: A Fail-Safe Example

What You'll Learn

You'll discover how CopyOnWriteArrayList provides a fail-safe iterator that never throws ConcurrentModificationException by working with an immutable snapshot.

The Fail-Safe Approach

Unlike ArrayList (which is fail-fast), CopyOnWriteArrayList takes a completely different approach to concurrent modifications. When you obtain an iterator from a CopyOnWriteArrayList, that iterator operates on an immutable snapshot of the list at the moment the iterator was created.

Think of it like taking a photograph of a document. Even if someone edits the original document afterward, your photograph remains unchanged. You can safely examine every detail in your photo without worrying about the original being modified.

How It Works

When you call iterator() on a CopyOnWriteArrayList, the iterator captures the current state of the list's internal array. Any modifications to the list after that point—additions, removals, or changes—don't affect the iterator. The iterator simply traverses its snapshot from beginning to end, never encountering surprises.

This means:

  • No ConcurrentModificationException: The iterator cannot detect modifications because it's working with its own copy
  • Stale data is possible: The iterator may show old data if the list was modified after iteration began
  • Ideal for read-heavy workloads: Perfect when you iterate frequently but modify rarely

Trade-Offs

The "copy-on-write" part means every modification creates a new copy of the internal array, making writes expensive. However, reads and iterations are fast and completely thread-safe without explicit synchronization.

Key Takeaway: CopyOnWriteArrayList provides fail-safe iteration through immutable snapshots—its iterator never throws exceptions because it operates on a frozen view of the collection, making it ideal for scenarios with many readers and few writers.