← Back to libraryQuestion 29 of 273
JavaAdvanced

Fail-Fast vs Fail-Safe Iterators

📖 Detailed Explanation:

Fail-Fast iterators (ArrayList, HashMap) throw ConcurrentModificationException if the collection is modified while iterating. Fail-Safe iterators (ConcurrentHashMap, CopyOnWriteArrayList) work on a copy or snapshot of the collection and don't throw exceptions, but may miss modifications made during iteration.

🌍 Real-World Example:

Fail-Fast: A librarian kicks you out if you try to add a new book while she's counting them. Fail-Safe: A librarian gives you a printed list of books that remains valid even if books are added later.

🎯 Scenario-Based Interview Question:

How does a Fail-Fast iterator know that the collection has been modified?