fail-fast 机制是java集合(Collection)中的一种错误机制。
fail-fast如何产生:
1.多个线程同时操作同一个collection
public static List<String> list =new ArrayList<String>();public static void main( String[] args ){ new Thread(new Runnable() { @Override public void run() { for (int i=0;i<10;i++ ){ list.add("c"+i); printAll(); } } }).start(); new Thread(new Runnable() { @Override public void run() { for (int i=0;i<10;i++ ){ list.add("d"+i); printAll(); } } }).start();}public static void printAll(){ for(String string: list){ System.out.println(string); }}
2.通过增强循环for(Object obj:collection)遍历collection 时同时修改collection
public static List<String> list =new ArrayList<String>();public static void main( String[] args ){ for (int i=0;i<10;i++ ){ list.add("d"+i); } printAll();}public static void printAll(){ for(String string: list){ System.out.println(string); list.remove(string); }}
通过ArrayList 源码
/** * An optimized version of AbstractList.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; Itr() {} 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(); } } @Override @SuppressWarnings("unchecked") 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(); }} //这段 final void checkForComodification() { if (modCount != expectedModCount) //modCount chushi throw new ConcurrentModificationException(); }
增强遍历时 使用的是arraylist 的实现的 Iterator 每次遍历的时候都会检查 arraylist修改的记录数是否一致 不一致就抛出ConcurrentModificationException异常
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦