Java Collection three Fail-fast

Source: Internet
Author: User
Tags concurrentmodificationexception

Fail-fast

The fail-fast mechanism is an error mechanism in the Java collection. Fail-fast events can occur when multiple threads operate on the contents of a unified collection.
?? When a thread traverses a collection through iterator, the thread of the collection is changed by another thread, and an exception is thrown, resulting in an fail-fast event.

Fail-fast Solutions

The fail-fast mechanism is an error detection mechanism used to detect errors, and the JDK does not guarantee that the fail-fast mechanism will occur. If you are using a collection of fail-fast mechanisms in a multithreaded environment, we recommend that you use classes under the Java.util.concurrent package.

Fail-fast principle
Package Java.util; Public Abstract classAbstractlist<e>extendsAbstractcollection<e>Implementslist<e> {...///Abstractlist Unique Properties    //Used to record the number of changes to the list: every modification (Add/delete operations) will modcount+1    protected transient intModcount =0;//Returns a list-corresponding iterator. In effect, the ITR object is returned.      PublicIterator<e>iterator() {return New Itr(); }//ITR is the implementation class of the iterator (iterator)    Private classItrImplementsiterator<e> {intcursor =0;intLastret =-1;//Modify the record value of the number.         //Each time a new ITR () object is created, the corresponding Modcount is saved when the object is created.        each time the elements in the list are traversed, the expectedmodcount and modcount are compared for equality;        //If not equal, throws an Concurrentmodificationexception exception, generating the Fail-fast event.         intExpectedmodcount = Modcount; Public Boolean Hasnext() {returnCursor! =size(); } PublicENext() {before the next element is fetched, it is determined whether the "Modcount saved when new ITR object" and "current Modcount" are equal;            //If not equal, throws an Concurrentmodificationexception exception, generating the Fail-fast event.             checkforcomodification();Try{E next =Get(cursor); Lastret = cursor++;returnNext }Catch(Indexoutofboundsexception e) {checkforcomodification();Throw NewNosuchelementexception (); }        } Public void Remove() {if(Lastret = =-1)Throw NewIllegalStateException ();checkforcomodification();Try{abstractlist. This.Remove(Lastret);if(Lastret < cursor) cursor--; Lastret =-1;            Expectedmodcount = Modcount; }Catch(Indexoutofboundsexception e) {Throw NewConcurrentmodificationexception (); }        }Final void checkforcomodification() {if(Modcount! = expectedmodcount)Throw NewConcurrentmodificationexception (); }    }    ...}

When next () and remove () are called, checkforcomodification () is executed. If Modcount is not equal to Expectedmodcount, an exception is thrown and the Fail-fast event is generated.
Expectedmodcount is assigned a value of Modcount when creating a Itr object. And Expectedmodcount cannot be modified, so you need to know when Modcount is changed.
View ArrayList source code, you can know that add (), remove () and other design to modify the number of elements in the collection of operations, will change the value of Modcount.

The principle of solving fail-fast

Take ArrayList corresponding Copyonwritearraylist as an example, by observing the source:
1, ArrayList inherit Abstractlist, and Copywritearraylist not inherit abstractlist, just implement the list interface
2. The iterator returned by the ArrayList iterator () function is implemented in Abstractlist, and Copyonwritearraylist is implemented by itself iterator
When next () is called in the iterator implementation class of ArrayList, "Checkforcomodification () is called to compare the size of ' expectedmodcount ' and ' modcount '; Copyonwritearraylist the iterator implementation class, there is no so-called checkforcomodification (), and the concurrentmodificationexception exception is not thrown
Copyonwritearraylist is synchronized with the Synchronized keyword for operations that change the elements of a collection, ensuring thread safety

Reference from: http://www.cnblogs.com/skywang12345/p/3323085.html

Java Collection three Fail-fast

Related Article

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.