故障安全迭代器和弱一致性迭代器 [英] fail safe iterators and weakly consistent iterators

查看:348
本文介绍了故障安全迭代器和弱一致性迭代器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

失败安全迭代器是不会 throw ConcurrentModificationException 的那些。



但是失败安全迭代器之间的区别是弱一致的迭代器



两者是否相同?

解决方案 / code>和微弱一致的迭代器不会引发 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


  1. Java泛型和集合:11.5。收藏和主题安全

  2. 迭代器 - 失败快速VS失败安全


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:

  1. Java Generics and Collections: 11.5. Collections and Thread Safety
  2. Iterators – Fail fast Vs Fail safe

这篇关于故障安全迭代器和弱一致性迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆