java.util.Collection的fail-fast機制

來源:互聯網
上載者:User

標籤: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機制

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.