本篇以ArrayList为例, 总结了Java中出现的Fail-Fast(快速失败)机制
前面, 我们已经学习了ArrayList的源码 . 接下来,我们以ArrayList为例,对Iterator的fail-fast机制进行了解, 内容包括:
fail-fast简介
fail-fast示例
fail-fast解决办法
fail-fast原理
JUC解决fail-fast的原理
Fail-Fast简介 fail-fast 机制是java集合(Collection)中的一种错误机制, 当某个线程在遍历集合时, 其他线程或本线程自身对同一个集合的内容进行操作时,就可能会产生fail-fast事件
例如:当某一个线程A通过iterator去遍历某集合的过程中,若该集合的内容被其他线程所改变了;那么线程A访问集合时,就会抛出ConcurrentModificationException异常,产生fail-fast事件
先通过一个示例来认识一下fail-fast
Fail-Fast示例 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 public class FastFailTest { private static List <String> list = new ArrayList <>(); public static void main (String[] args) { new ThreadOne ().start(); new ThreadTwo ().start(); } private static void printAll () { System.out.println(); for (String s : list) { System.out.print(s + ", " ); } } private static class ThreadOne extends Thread { @Override public void run () { int i = 0 ; while (i < 6 ) { list.add(String.valueOf(i)); printAll(); i++; } } } private static class ThreadTwo extends Thread { @Override public void run () { int i = 10 ; while (i < 16 ) { list.add(String.valueOf(i)); printAll(); i++; } } } }
运行结果 : <font color=”#ff0000”运行该代码,抛出异常java.util.ConcurrentModificationException, 即,产生fail-fast事件
结果说明 :
① FastFailTest中通过 new ThreadOne().start() 和 new ThreadTwo().start() 同时启动两个线程去操作list:
ThreadOne线程 :向list中依次添加0,1,2,3,4,5。每添加一个数之后,就通过printAll()遍历整个list
ThreadTwo线程 :向list中依次添加10,11,12,13,14,15。每添加一个数之后,就通过printAll()遍历整个list
② 当某一个线程遍历list的过程中,list的内容被另外一个线程所改变了;就会抛出ConcurrentModificationException异常,产生fail-fast事件
三. Fail-Fast解决办法 fail-fast机制,是一种错误检测机制。它只能被用来检测错误,因为JDK并不保证fail-fast机制一定会发生。
若在多线程环境下使用fail-fast机制的集合,建议使用java.util.concurrent包下的类去取代java.util包下的类. 所以, 本例中只需要将ArrayList替换成java.util.concurrent包下对应的类即可:
1 private static List<String> list = new ArrayList<String>();
替换为
1 private static List<String> list = new CopyOnWriteArrayList<String>();
则可以解决该问题
四. Fail-Fast原理 产生fail-fast事件,是通过抛出ConcurrentModificationException异常来触发的. 那么,ArrayList是如何抛出ConcurrentModificationException异常的呢?
我们知道,ConcurrentModificationException是在操作Iterator时抛出的异常, 而ArrayList的Iterator是在父类AbstractList中实现的, 所以我们不妨先看看AbstractList的源代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 public abstract class AbstractList <E> extends AbstractCollection <E> implements List <E> { ... protected transient int modCount = 0 ; public Iterator <E> iterator () { return new Itr (); } private class Itr implements Iterator <E> { int cursor = 0 ; int lastRet = -1 ; int expectedModCount = modCount; public boolean hasNext () { return cursor != size(); } public E next () { checkForComodification(); try { E next = get(cursor); lastRet = cursor++; return next; } catch (IndexOutOfBoundsException e) { checkForComodification(); throw new NoSuchElementException (); } } public void remove () { if (lastRet == -1 ) throw new IllegalStateException (); checkForComodification(); try { AbstractList.this .remove(lastRet); if (lastRet < cursor) cursor--; lastRet = -1 ; expectedModCount = modCount; } catch (IndexOutOfBoundsException e) { throw new ConcurrentModificationException (); } } final void checkForComodification () { if (modCount != expectedModCount) throw new ConcurrentModificationException (); } } ... }
从中,我们可以发现在调用 next() 和 remove()时,都会执行 checkForComodification(): 若 “modCount 不等于 expectedModCount”,则抛出ConcurrentModificationException异常,产生fail-fast事件
而从Itr类中,我们知道 expectedModCount 在创建Itr对象时,被赋值为 modCount。所以,需要考证的就是modCount何时会被修改。
接下来,我们查看ArrayList的源码,来看看modCount是如何被修改的:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 public class ArrayList <E> extends AbstractList <E> implements List <E>, RandomAccess, Cloneable, java.io.Serializable { ... public void ensureCapacity (int minCapacity) { modCount++; int oldCapacity = elementData.length; if (minCapacity > oldCapacity) { Object oldData [] = elementData; int newCapacity = (oldCapacity * 3 )/2 + 1 ; if (newCapacity < minCapacity) newCapacity = minCapacity; elementData = Arrays.copyOf(elementData, newCapacity); } } public boolean add (E e) { ensureCapacity(size + 1 ); elementData[size++] = e; return true ; } public void add (int index, E element) { if (index > size || index < 0 ) throw new IndexOutOfBoundsException ( "Index: " +index+", Size: " +size); ensureCapacity(size+1 ); System.arraycopy(elementData, index, elementData, index + 1 , size - index); elementData[index] = element; size++; } public boolean addAll (Collection<? extends E> c) { Object [] a = c.toArray(); int numNew = a.length; ensureCapacity(size + numNew); System.arraycopy(a, 0 , elementData, size, numNew); size += numNew; return numNew != 0 ; } public E remove (int index) { RangeCheck(index); modCount++; E oldValue = (E) elementData[index]; int numMoved = size - index - 1 ; if (numMoved > 0 ) System.arraycopy(elementData, index+1 , elementData, index, numMoved); elementData[--size] = null ; return oldValue; } private void fastRemove (int index) { modCount++; int numMoved = size - index - 1 ; if (numMoved > 0 ) System.arraycopy(elementData, index+1 , elementData, index, numMoved); elementData[--size] = null ; } public void clear () { modCount++; for (int i = 0 ; i < size; i++) elementData[i] = null ; size = 0 ; } ... }
从中,我们发现:无论是add()、remove(),还是clear(),只要涉及到修改集合中的元素个数时,都会改变modCount的值
即: 当多个线程对同一个集合进行操作的时候,某线程访问集合的过程中,该集合的内容被其他线程所改变(即其它线程通过add、remove、clear等方法,改变了modCount的值);这时,就会抛出ConcurrentModificationException异常,产生fail-fast事件
五. JUC解决fail-fast的原理 上面,说明了解决fail-fast机制的办法,也知道了fail-fast产生的根本原因, 接下来,我们再进一步谈谈java.util.concurrent包中是如何解决fail-fast事件的
还是以和ArrayList对应的CopyOnWriteArrayList进行说明, 我们先看看CopyOnWriteArrayList的源码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public class CopyOnWriteArrayList <E> implements List <E>, RandomAccess, Cloneable, java.io.Serializable { ... public Iterator <E> iterator () { return new COWIterator <E>(getArray(), 0 ); } ... private static class COWIterator <E> implements ListIterator <E> { private final Object[] snapshot; private int cursor; private COWIterator (Object[] elements, int initialCursor) { cursor = initialCursor; snapshot = elements; } public boolean hasNext () {...} public boolean hasPrevious () {...} public E next () {...} public E previous () {...} public int nextIndex () {...} public int previousIndex () {...} public void remove () {...} public void set (E e) {...} public void add (E e) {...} } ... }
从中,我们可以看出:
① 和ArrayList继承于AbstractList不同,CopyOnWriteArrayList没有继承于AbstractList,它仅仅只是实现了List接口;
② ArrayList的iterator()函数返回的Iterator是在AbstractList中实现的;而CopyOnWriteArrayList是自己实现Iterator;
③ ArrayList的Iterator实现类中调用next()时,会调用checkForComodification()比较expectedModCountmodCount的大小”;但是,CopyOnWriteArrayList的Iterator实现类中,没有所谓的checkForComodification(),更不会抛出ConcurrentModificationException异常!