Exception in Thread "Thread-1" Java.util.ConcurrentModificationException exception causes and workarounds

Source: Internet
Author: User
Tags concurrentmodificationexception

Note: Reference blog: https://www.cnblogs.com/dolphin0520/p/3933551.html
1. Abnormal recurrence in single-thread environment

    public static void Main (string[] args)  {        arraylist<integer> list = new arraylist<integer> ();        List.add (2);        iterator<integer> Iterator = List.iterator ();        while (Iterator.hasnext ()) {            integer integer = Iterator.next ();            if (integer==2) {                list.remove (integer);                Iterator.remove ();   Correct notation            }}}    

When the while (Iterator.hasnext ()) loop is traversed, only the last element of the ArrayList internal elementdata[] is allowed to be deleted, but not removed from the middle.
In the source code of Iterator.next (), the method is executed first: Checkforcomodification (); This method:

final void Checkforcomodification () {            if (modcount! = expectedmodcount)                throw new Concurrentmodificationexception ();        }

Only if the values of the two variables are equal do not error. and List.add (2) operation and List.remove (integer);   Operation will make modcount++;  But the variable expectedmodcount is the variable of the ITR subclass of the inner class, the instantiation method of the subclass is: List.iterator (); An instance object is assigned an initial value:
int expectedmodcount = Modcount; Therefore, it is not allowed to have List.add (2) operation and List.remove (integer) within the while (Iterator.hasnext ()) loop method, or it will cause expectedmodcount! = Modcount, which in turn leads to the throw of the new Concurrentmodificationexception ();

Exception in Thread "Thread-1" Java.util.ConcurrentModificationException exception causes and workarounds

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.