Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fail safe iterators and weakly consistent iterators

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?

like image 476
a Learner Avatar asked Nov 22 '13 10:11

a Learner


1 Answers

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:

  1. Java Generics and Collections: 11.5. Collections and Thread Safety
  2. Iterators – Fail fast Vs Fail safe
like image 141
Sage Avatar answered Oct 07 '22 12:10

Sage