fail safe iterators and weakly consistent iterators

后端 未结 1 1309
遥遥无期
遥遥无期 2020-12-31 04:32

Fail safe iterators are those which do not throw ConcurrentModificationException.

But what is the difference between fail safe iterat

相关标签:
1条回答
  • 2020-12-31 05:15

    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
    0 讨论(0)
提交回复
热议问题