java-----ArrayList的fail-fast机制学习

来源:互联网 发布:淘宝钢笔店 编辑:程序博客网 时间:2024/06/05 15:38

        java中经常会用到容器类,他们为我们实际的开发提供了很大的便捷,但是在使用的过程中经常会出现一些奇奇怪怪的异常,今天演示的就是使用ArrayList过程中出现的一个异常,就是我们经常会遇到的ConcurrentModificationException异常了,这个异常会在我们多线程并发修改ArrayList,并且至少有一个线程在迭代输出ArrayList里面的值的时候出现,下面我们再现一下出错场景,随后从源码角度来分析问题原因以及解决方法;

        问题再现:

public class FailFastTest {public static ArrayList<Integer> list = new ArrayList<>();public static void main(String[] args) {AddRunnable addRunnable = new AddRunnable();IteratorRunnable iteratorRunnable = new IteratorRunnable();new Thread(addRunnable).start();new Thread(iteratorRunnable).start();}static class AddRunnable implements Runnable{@Overridepublic void run() {int sum = 10;while(sum > 0){list.add(sum);sum--;try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}}}}static class IteratorRunnable implements Runnable{@Overridepublic void run() {try {Thread.sleep(15);} catch (InterruptedException e) {e.printStackTrace();}Iterator<Integer> it = list.iterator();while(it.hasNext()){System.out.println(it.next());try {Thread.sleep(15);} catch (InterruptedException e) {e.printStackTrace();}}}}}
        AddRunnable是用于向ArrayList中添加数据的,IteratorRunnable用于迭代输出ArrayList的值,为了模拟效果,我们在AddRunnable中每隔10ms添加一条数据,在IteratorRunnable中每隔15ms会查看Iterator里面有没有next值,最终看到下面输出:

10Exception in thread "Thread-1" java.util.ConcurrentModificationExceptionat java.util.ArrayList$Itr.checkForComodification(Unknown Source)at java.util.ArrayList$Itr.next(Unknown Source)at com.hzw.test.FailFastTest$IteratorRunnable.run(FailFastTest.java:46)at java.lang.Thread.run(Unknown Source)
        也就是发生了我们所说的fail-fast,即AddRunnable线程在操作ArrayList的同时,IteratorRunnable在迭代,但是数组里面的元素值却是在不断的变化,导致了马上抛出异常,下面我们分析下产生这种现象的原因:

        由于我们采用的是ArrayList做的测试,所以查看ArrayList源码即可,在上面抛出异常的输出中你会发现异常是出现在checkForComodification方法里面的,具体是在调用ArrayList$Itr.next方法的时候会调用checkForComodification方法,进而产生异常,那么这里的Itr又是什么呢?查看源码发现他是ArrayList的私有内部类,我们在调用ArrayList的iterator方法的时候会创建一个Itr对象出来,查看源码如下:

public Iterator<E> iterator() {        return new Itr();    }
        那好,我们就该从Itr看起了,因为异常是在他的方法里面抛出的,因为该类的源码不太长,我贴出来吧:

    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;        public boolean hasNext() {            return cursor != size;        }        @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];        }        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();            }        }        final void checkForComodification() {            if (modCount != expectedModCount)                throw new ConcurrentModificationException();        }    }

        在第4行有一个很重要的赋值操作,int expectedModCount = modCount,那么这里的modCount指的是什么呢?看看官方注释:

The number of times this list has been structurally modified. 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.
        什么意思呢?意思是说modCount是指list在结构上被改变的次数当然也包括list中内容顺序发生改变的次数,这个值的修改会使得迭代器产生不正确的结果,如果你查看ArrayList中modCount值哪里发生过修改的话,一般出现在add、remove、clear中;

        同时你会发现在Itr中的每个方法执行之前都会调用checkForComodification,很自然我们该看看checkForComodification里面是什么样子了,查看上面的源码就知道原来里面就是判断expectedModCount与modCount是否相等了,不等的话就会抛出上面我们看到的异常了,而expectedModCount的值是我们在开始迭代的时候赋值的,modCount有可能在我们迭代的过程中因为我们向ArrayList中添加或者删除元素而发生变化,这就会导致两者值不等了,也就是我们上面出现的情况了;

        那么这个问题该怎么解决呢?很简单的一种方式就是将ArrayList替换成CopyOnWriteArrayList,其实这点从两者所引用的包路径就可以看出来了,ArrayList引用自java.util而CopyOnWriteArrayList引用自java.util.concurrent,而concurrent就是并发的意思啦!那么CopyOnWriteArrayList能够避免上述并发操作ArrayList带来的问题原理是什么呢?看来我们有必要看看CopyOnWriteArrayList的源码了:

        同样它里面也有一个Iterator方法,和ArrayList一样,他也实现了List接口,因为Iterator是属于List接口的,所以他也相应的需要实现Iterator方法啦:      

   public Iterator<E> iterator() {        return new COWIterator<E>(getArray(), 0);    }
        查看他的Iterator方法,发现返回一个COWIterator对象,COWIterator是CopyOnWriteArrayList的私有内部静态类,我们来看看它里面的源码:

private static class COWIterator<E> implements ListIterator<E> {        /** Snapshot of the array */        private final Object[] snapshot;        /** Index of element to be returned by subsequent call to next.  */        private int cursor;        private COWIterator(Object[] elements, int initialCursor) {            cursor = initialCursor;            snapshot = elements;        }        public boolean hasNext() {            return cursor < snapshot.length;        }        public boolean hasPrevious() {            return cursor > 0;        }        @SuppressWarnings("unchecked")        public E next() {            if (! hasNext())                throw new NoSuchElementException();            return (E) snapshot[cursor++];        }        @SuppressWarnings("unchecked")        public E previous() {            if (! hasPrevious())                throw new NoSuchElementException();            return (E) snapshot[--cursor];        }        public int nextIndex() {            return cursor;        }        public int previousIndex() {            return cursor-1;        }        /**         * Not supported. Always throws UnsupportedOperationException.         * @throws UnsupportedOperationException always; <tt>remove</tt>         *         is not supported by this iterator.         */        public void remove() {            throw new UnsupportedOperationException();        }        /**         * Not supported. Always throws UnsupportedOperationException.         * @throws UnsupportedOperationException always; <tt>set</tt>         *         is not supported by this iterator.         */        public void set(E e) {            throw new UnsupportedOperationException();        }        /**         * Not supported. Always throws UnsupportedOperationException.         * @throws UnsupportedOperationException always; <tt>add</tt>         *         is not supported by this iterator.         */        public void add(E e) {            throw new UnsupportedOperationException();        }    }
        注意到的是COWIterator没有无参构造器,唯一的构造函数就在第7行了,也就是上面iterator调用的构造函数了,在这个构造函数里面,第一个传入的参数是我们的数组拷贝,这点需要注意一下啦,也就是iterator里面第一个参数getArray()的值实际上就是我们当前数组的一份拷贝,然后传递给COWIterator之后,看到将getArray()参数传入的数组地址赋给了snapshot,然后接下来的所有操作都是针对snapshot也就是getArray拷贝数组的,并不会对原来的数组有任何修改,这就保证了我们迭代过程中数组中的内容不会发生变化了,也就是说我迭代是迭代的原先数组的拷贝,并不是原先数组,注意这里的拷贝是数组地址也发生了变化的,不仅仅将原先数组地址赋给拷贝地址,这点从CopyOnWriteArrayList里面任意一个修改list的方法中都能看出来,我们以add方法为例:

public boolean add(E e) {        final ReentrantLock lock = this.lock;        lock.lock();        try {            Object[] elements = getArray();            int len = elements.length;            Object[] newElements = Arrays.copyOf(elements, len + 1);            newElements[len] = e;            setArray(newElements);            return true;        } finally {            lock.unlock();        }    }
        可以看到第7行调用了Arrays.copyof方法,这个方法就是用来进行数组拷贝的,这个拷贝完之后生成的数组和原先的数组地址值是不一样的,并且使用setArray将数组值保存下来,随后的迭代过程中使用的就是这个拷贝数组了;

        至此关于fail-fast机制出现的原因以及解决的方法已经整理结束了,希望有不对的地方大家能够批评指正!!!!!







0 0