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

What Is Fail-Fast Behavior?

Understand how fail-fast iterators throw ConcurrentModificationException when the collection is modified during iteration.

What Is Fail-Fast Behavior?

You'll learn how Java's iterators detect concurrent modifications and protect you from unpredictable behavior during iteration.

The Core Idea

Fail-fast behavior means that when you're iterating over a collection and that collection gets modified (outside the iterator itself), the iterator immediately throws a ConcurrentModificationException rather than continuing with potentially corrupted data. It's Java's way of saying "Stop! Something changed underneath you—I can't guarantee correct behavior anymore."

Why It Matters

Imagine you're walking through a museum gallery, counting paintings. If someone starts removing paintings while you're counting, your final count will be wrong. Fail-fast iterators detect this "structural modification" and fail immediately rather than giving you incorrect results.

When you obtain an iterator from most Java collections (like ArrayList, HashMap, HashSet), the collection tracks a modification count. Every time the collection structure changes—elements added, removed, or cleared—this count increments. The iterator remembers the count from when it was created. Before each next() or remove() call, the iterator checks: "Does my saved count still match the collection's count?" If not, it throws ConcurrentModificationException.

What Triggers It

Modifications that bypass the iterator itself trigger fail-fast:

  • Calling list.add() or list.remove() while iterating
  • Another thread modifying the collection
  • Multiple iterators where one calls remove()

Using the iterator's own remove() method is safe—it updates the modification count properly.

Important Caveat

Fail-fast is a best-effort detection mechanism, not a guarantee. It's designed to catch bugs during development, not to be relied upon for program correctness in production.

Key Takeaway: Fail-fast iterators throw ConcurrentModificationException when they detect the collection was modified during iteration (except via the iterator's own methods), helping you catch bugs early rather than producing silent incorrect results.