Fail safe iterators are those which do not throw
ConcurrentModificationException
.
But what is the difference between fail safe iterators
and weakly consistent iterators
?
Are both same?
Both Fail-safe
and Weakly consistent
iterators do not throw ConcurrentModificationException
.
weakly consistent iterators:
Collections which rely on CAS(compare-and-swap) have weakly consistent iterators, which reflect some but not necessarily all of the changes that have been made to their backing collection since they were created. For example, if elements in the collection have been modified or removed before the iterator reaches them, it definitely will reflect these changes, but no such guarantee is made for insertions.
Fail safe iterator
iterator mechanism makes a copy of the internal Collection data structure and uses it to iterate over the elements. This prevents any concurrent modification exceptions from being thrown if the underlying data structure changes. Of course, the overhead of copying the entire array is introduced.
CopyOnWriteArrayList
is one such implementation with Fail safe iterator, which we can easily see by looking at the constructor's source:
public CopyOnWriteArrayList(Collection<? extends E> c) {
Object[] elements = c.toArray();
if (elements.getClass() != Object[].class)
elements = Arrays.copyOf(elements, elements.length, Object[].class);
setArray(elements);
}
Reference:
Java Generics and Collections: 11.5. Collections and Thread Safety
Iterators – Fail fast Vs Fail safe
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With