Reputation: 7996
Before asking this question I have tried understanding (here on SOF and on some other websites) fail-safe feature. I understand Java Collection Iterators are fail-fast, which basically means they fail gracefully as soon as underlying Collection is being structurally modified (even by the same thread). My question is does fail-safe property have anything to do with Iterators' remove() or add() features? In my understanding because through Iterators you can add or remove (safely) while iterating over a Collection and you wont get a concurrent exception (that you do without using their remove and add features), so that makes Iterators fail-safe. Or I have got it completely wrong?
Thanks!
Upvotes: 0
Views: 1294
Reputation: 2545
Not exactly. In my understanding fail-safe iterators work on snapshots of data and guarantee consistent view of the represented collection on the moment when the iterator has been created. (please see this blog post for more detailed treatment of this question). This property is guaranteed f.i. by iterators of the CopyOnWriteArrayList
. It's iterators do not support collection modification operations and its javadoc clarifies their behavior further:
This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw ConcurrentModificationException. The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (remove, set, and add) are not supported. These methods throw UnsupportedOperationException.
UPDATE:
When talking about fail-safeness and fail-fastness it is important to separate "the failure". In case of iterator there are different cases and hazards. As for the linked article I would say that there author implements fail-safe and fail-fast iteration at the first place by implementing iterators.
The failure in that case can be defined as concurrent modification of the iterated collection. When the collection is modified then fail-fast approach will be to stop iteration and to make the caller aware of the changed conditions (via CME
or by some other means).
When dealing with the same use-case and hazard we can move forward and think about fail-safe iteration. Fail-safeness property means that iteration should comply to its contract as long as it possible (and authors of the COWAS
succeed by copying underlying data).
Upvotes: 2
Reputation: 533640
The Iterator
or ListIterator
work on the underlying collection is a way which doesn't not invalidate that Iterator. Any modification via any other iterator or the collection itself, invalidates the iterator for some collections. Some collections are designed for concurrent access and don't have this restriction.
Upvotes: 0