What is the difference between fail-fast and fail-safe iterators?
The key difference between fail-fast and fail-safe iterators lies in how they behave when the underlying collection is modified during iteration:
- Fail-fast iterators:
- Throw a
ConcurrentModificationException
if the collection is modified while iterating (except through the iterator itself). - Example:
ArrayList
,HashMap
. - Provides early detection of concurrent modifications, which helps prevent inconsistent state.
- Throw a
- Fail-safe iterators:
- Do not throw exceptions if the collection is modified during iteration.
- They operate on a copy of the collection, so modifications to the original collection don’t affect the iterator.
- Example:
CopyOnWriteArrayList
,ConcurrentHashMap
.
In summary, fail-fast iterators detect modifications immediately and throw an exception, while fail-safe iterators allow modifications without issues, typically at the cost of performance due to copying the collection.