面试官:说说快速失败和安全失败是什么

65 阅读2分钟

1. 快速失败(fail-fast)

已知Collection接口实现了Iterator接口,在源码中也提到了fail-fast的概念 具体效果我们看下代码:

HashMap hashMap = new HashMap();
        hashMap.put("不只Java-1", 1);
        hashMap.put("不只Java-2", 2);
        hashMap.put("不只Java-3", 3);

        Set set = hashMap.entrySet();
        Iterator iterator = set.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            hashMap.put("下次循环会抛异常", 4);
            System.out.println("此时 hashMap 长度为" + hashMap.size());
        }

执行后的效果如下图:

为什么在用迭代器遍历时,修改集合就会抛异常时?

原因是迭代器在遍历时直接访问集合中的内容,并且在遍历过程中使用一个 modCount 变量。集合在被遍历期间如果内容发生变化,就会改变 modCount 的值。

每当迭代器使用 hashNext()/next() 遍历下一个元素之前,都会检测 modCount 变量是否为 expectedModCount 值,是的话就返回遍历;否则抛出异常,终止遍历。

源码如下

public void forEachRemaining(Consumer<? super E> consumer) {
        Objects.requireNonNull(consumer);
        final int size = ArrayList.this.size;
        int i = cursor;
        if (i >= size) {
            return;
        }
        final Object[] elementData = ArrayList.this.elementData;
        if (i >= elementData.length) {
            throw new ConcurrentModificationException();
        }
        while (i != size && modCount == expectedModCount) {
            consumer.accept((E) elementData[i++]);
        }
        // update once at end of iteration to reduce heap write traffic
        cursor = i;
        lastRet = i - 1;
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

2.安全失败

明白了什么是快速失败之后,安全失败也是非常好理解的。

采用安全失败机制的集合容器,在遍历时不是直接在集合内容上访问的,而是先复制原有集合内容,在拷贝的集合上进行遍历。

由于迭代时是对原集合的拷贝进行遍历,所以在遍历过程中对原集合所作的修改并不能被迭代器检测到,故不会抛 ConcurrentModificationException 异常

我们上代码看下是不是这样

ConcurrentHashMap concurrentHashMap = new ConcurrentHashMap();
        concurrentHashMap.put("不只Java-1", 1);
        concurrentHashMap.put("不只Java-2", 2);
        concurrentHashMap.put("不只Java-3", 3);

        Set set = concurrentHashMap.entrySet();
        Iterator iterator = set.iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
            concurrentHashMap.put("下次循环正常执行", 4);
        }
        System.out.println("程序结束");

运行效果如下,的确不会抛异常,程序正常执行。

最后说明一下,快速失败和安全失败是对迭代器而言的。并发环境下建议使用 java.util.concurrent 包下的容器类,除非没有修改操作。