码迷,mamicode.com
首页 > 编程语言 > 详细

java.util.Collection的fail-fast机制

时间:2018-08-16 15:41:56      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:ide   一个   illegal   Once   catch   traffic   main   产生   iter   

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异常

java.util.Collection的fail-fast机制

标签:ide   一个   illegal   Once   catch   traffic   main   产生   iter   

原文地址:http://blog.51cto.com/5013162/2160740

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!