关于快速报错fail-fast想说的之fail-fast的实现原理(一)

最近在翻译HashMap的源码注释,看到了fail-fast。之前在看第四版《Thinking in java》的第17章容器深入研究 17.11.3中的“快速报错”时就有些迷迷糊糊,今天查了下资料,总结总结。

注意,本文的讨论都是基于JDK 1.8的。
这里写图片描述

结论

快速报错,是指当有其他线程对一个容器(如ArrayList,HashMap)进行了结构性修改,另外一个线程在使用iterator进行迭代,那么这个迭代线程会抛出并发修改的异常ConcurrentModificationException。
所谓结构性修改,是对原有容器的size造成影响的操作,如remove、add、clear操作等。

示例代码(一)

1.代码

    public static void main(String[] args) {
        //这会报不支持的操作异常,UnsupportedOperationException
        //因为,Arrays.assList的底层实现是使用数组实现的,而数组不支持remove操作。
        String string = "a b c d e";
        List<String> stringList = Arrays.asList(string.split(" "));
        Iterator<String> iterator = stringList.iterator();
        while (iterator.hasNext()) {
            if(iterator.next().equals("c")) {
                stringList.remove("c");
            }
        }
    }

2.执行结果
这里写图片描述
报错的代码行数对应的代码是stringList.remove("c"); 这句话。
3.解析
原因在于List<String> stringList = Arrays.asList(string.split(" ")); 这句话。ArrayList.asList返回的List是固定大小的List,也就是说不可以对其进行add、remove操作。
ArrayList.asList的源码实现如下:

    //Returns a fixed-size list backed by the specified array.
    @SafeVarargs
    @SuppressWarnings("varargs")
    public static <T> List<T> asList(T... a) {
        return new ArrayList<>(a);
    }

    //该ArrayList类不是java.util包中的内容,而是Arrays类的内部类。
    private static class ArrayList<E> extends AbstractList<E>
        implements RandomAccess, java.io.Serializable
    {
        private static final long serialVersionUID = -2764017481108945198L;
        private final E[] a;

        ArrayList(E[] array) {
            a = Objects.requireNonNull(array);
        }

        /*省略此处代码*/

    }

从上面代码的注释中可以看到是 “返回的是固定大小的List”。从源码实现上可以看到,private final E[] a; ,内部类ArrayList中的成员变量a,是final的。

示例代码(二)

注意,这个示例代码中的ArrayList不是上一个示例中出现的内部类,而是java.util.ArrayList。
1.代码

    public static void main(String[] args) {
        String string = "a b c d e";
        List<String> stringList1 = Arrays.asList(string.split(" "));
        //这个会得到  并发修改异常  ConcurrentModificationException
        List<String> stringList = new ArrayList<String>(stringList1);
        System.out.println(stringList);

        Iterator<String> iterator = stringList.iterator();
        while (iterator.hasNext()) {
            if(iterator.next().equals("c")) {
                stringList.remove("c");
            }
        }
    }

2.执行结果
这里写图片描述
3.解析
从抛异常的报告上对应的代码是if(iterator.next().equals("c")) { 这一行。从调用栈来看,是在java.util.ArrayList的内部类Itr的next方法在调用checkForComodification方法时抛的异常。
来看看java.util.ArrayList的相关源码实现。

private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such
        int expectedModCount = modCount;

        @SuppressWarnings("unchecked")
        public E next() {
            checkForComodification();
            int i = cursor;
            if (i >= size)
                throw new NoSuchElementException();
            Object[] elementData = ArrayList.this.elementData;
            if (i >= elementData.length)
                throw new ConcurrentModificationException();
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

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

        /**省略此处代码**/

    }

其中的modCount是ArrayList的一个属性。

     /*
     * The number of times this list has been <i>structurally modified</i>.
     * Structural modifications are those that change the size of the
     * list, or otherwise perturb it in such a fashion that iterations in
     * progress may yield incorrect results.
     * /
    protected transient int modCount = 0;

transient关键字,说明ArrayList在序列化时,不包含modCound属性。源码给的注释可以看到,modCount用来表示list被结构性修改的次数。所谓结构性修改是指,改变了list的size,或者在迭代过程中产生了不正确的结果。
内部类在被示例化时会将modCount赋值给expectedModCount。
内部类的实例化发生在ArrayList的iterator被调用的时候,即Iterator<String> iterator = stringList.iterator(); 这句话执行时初始化的。看看ArrayList#iterator的实现:

    public Iterator<E> iterator() {
        return new Itr();
    }

从next方法的实现上可以看到,首先就会判断expectedModCount与modCount是否相等,如果不等就会抛ConcurrentModificationException异常。不相等说明其他线程修改了modCount。当然,在这个例子中只有main线程,也出现了这种情况。因为,在迭代到”c”时,stringList.remove("c"); 执行了remove操作,对list造成了结构性修改,改变了list的size,modCount的值会加1。这样当迭代到”d”时,发现expectedModCount与modCount不等了,因此抛异常了。

代码示例(三)

1.代码:

    public static void main(String[] args) {
        String string = "a b c d e";
        List<String> stringList1 = Arrays.asList(string.split(" "));
        List<String> stringList = new ArrayList<String>(stringList1);
        System.out.println(stringList);

        Iterator<String> iterator = stringList.iterator();
        while (iterator.hasNext()) {
            if(iterator.next().equals("c")) {
                //这里跟上例不同,上例为stringList.remove("c");
                iterator.remove();
            }
        }
        System.out.println(stringList);
    }

2.执行结果
这里写图片描述
3.解析
可以看到,使用iterator.remove()没有抛异常,而且成功修改stringList的内容。
来看看ArrayList#Itr#remove方法的实现。

    private class Itr implements Iterator<E> {

        /**省略此处代码**/

        public void remove() {
            if (lastRet < 0)
                throw new IllegalStateException();
            checkForComodification();

            try {
                ArrayList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
                expectedModCount = modCount;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }
        /**省略此处代码**/    
    }

从上面代码可以看到,首先也判断了expectedModCount与modCount是否相等,但是这时还没有执行remove操作,因此不会抛异常。在执行了ArrayList.this.remove(lastRet); 之后,有一个关键的一行expectedModCount = modCount; 更新了expectedModCount的值。
下面来看看ArrayList#remove()方法的实现。

    public E remove(int index) {
        rangeCheck(index);

        modCount++;
        E oldValue = elementData(index);

        int numMoved = size - index - 1;
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index, numMoved);
        elementData[--size] = null; // clear to let GC do its work

        return oldValue;
    }

首先执行了modCount++; , 之后在本地修改elementData的内容,最后elementData[--size] = null; 便于垃圾回收。

结束语

再写就太长了。
这篇博文讨论了ArrayList在迭代过程中,如果有其他线程对list进行了结构性修改(当然如果在自己线程中执行顺序安排不当,也会抛异常),会抛出异常。讨论了下fail-fast的实现原理。下篇文章 关于快速报错fail-fast想说的之fail-fast的避免方法(二) 针对ArrayList的问题,找出解决方案以及一个关于HashMap fail-fast的例子。

参考资料:
1. Java中Iterator的fast-fail分析
2. Java提高篇(三四)—–fail-fast机制
3. 《Thinking in java》

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值