The fail-fast mechanism of java.util.Collection

Source: Internet
Author: User

The fail-fast mechanism is an error mechanism in the Java Collection (Collection).
Fail-fast How to produce:
1. Multiple threads simultaneously operate the same 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. Modify collection while traversing collection through enhanced loop for (Object obj: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);    }}

Through ArrayList source code

 /** * 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&LT;? 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 concurrentmodific ationException (); }}//This paragraph of final void Checkforcomodification () {if (Modcount! = expectedmodcount)//modcount            Chushi throw new Concurrentmodificationexception (); }

Enhanced traversal uses the implementation of the ArrayList Iterator each time the traversal is checked to see if the ArrayList modified record count is inconsistent and throws a Concurrentmodificationexception exception

The fail-fast mechanism of java.util.Collection

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.