读书人

聚合初探-Fail-Fast机制

发布时间: 2012-11-03 10:57:44 作者: rapoo

集合初探--Fail-Fast机制
Fail-Fast机制

在系统发生错误后,立即作出响应,阻止错误继续发生。

集合中的“Fail-Fast”机制

集合在其返回遍历器(Iterator)后任何时候发生变化,将会导致遍历器抛出ConcurrentModificationException异常的机制。
这种变化不包括遍历器本身调用remove方法移除元素。
ConcurrentModificationException异常不一定要并发下才会产生。比如:

        Map map = new HashMap();        for (int i = 1; i < 10; i++) {            map.put(i, i);        }        for (Iterator ite = map.entrySet().iterator(); ite.hasNext();) {            Map.Entry entry = (Map.Entry) ite.next();// 抛出异常位置            // // 调用Iterator.remove()不会抛出异常            // ite.remove();            // 调用map.remove()会抛出异常            map.remove(entry.getKey());         }       

代码实现是通过modCount域,记录修改次数,对集合内容的修改都会增加这个值,迭代器初始化过程中会将这个值赋给迭代器的expectedModCount。
        HashIterator() {            expectedModCount = modCount;            if (size > 0) { // advance to first entry                Entry[] t = table;                while (index < t.length && (next = t[index++]) == null)                    ;            }        }

在迭代过程中,判断modCount跟expectedModCount是否相等,如果不相等就表示集合已经发生变化,抛出异常。
    final Entry<K,V> nextEntry() {           if (modCount != expectedModCount)               throw new ConcurrentModificationException();     }

在非同步的并发修改时,迭代器的快速失败行为不可能作出任何坚决的保证。因此,编写依赖于此异常的程序的做法是错误的。

读书人网 >网络基础

热点推荐