故障安全迭代器和弱一致性迭代器 [英] fail safe iterators and weakly consistent iterators
问题描述
失败安全迭代器是不会 throw
ConcurrentModificationException
的那些。
但是失败安全迭代器
和之间的区别是弱一致的迭代器
?
两者是否相同?
微弱一致的
迭代器不会引发 ConcurrentModificationException
。 弱一致的迭代器:
依靠CAS( compare-and-swap 弱一致的迭代器,它们反映了自创建以来对它们的后台收集进行的一些但不一定是所有的更改。例如,如果集合中的元素在迭代器到达它们之前已被修改或删除,那么它肯定会反映这些更改,但不会对插入做出这样的保证。
失败安全迭代器
迭代器机制创建内部集合数据结构的副本,使用它来遍历元素。这防止了如果底层数据结构更改,则抛出任何并发修改异常。当然,引入了复制整个数组的开销。
CopyOnWriteArrayList
,我们可以通过查看构造函数的源来容易地看到:
public CopyOnWriteArrayList(Collection< ;? extends E> c){
Object [] elements = c.toArray();
if(elements.getClass()!= Object []。class)
elements = Arrays.copyOf(elements,elements.length,Object []。
setArray(elements);
}
参考: b
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
这篇关于故障安全迭代器和弱一致性迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!