Java concurrentmodificationexception exception Causes and workarounds

Source: Internet
Author: User

Questions:When iterating over the set, the Java.util.ConcurrentModificationException exception is thrown if it is modified at the same time;

cause Analysis:Enter the error message, locate the LinkedHashMap719 line, Modcount! = Expectedmodcount throw an exception.

Modcount is a member variable in the HashMap class that represents the number of modifications to the map, and each call to the put () method or the Remove () method adds 1 to the Modcount;

Expectedmodcount: Represents the expected value of the number of map modifications, and its initial values are Modcount

When the processes in diagram one is traversed,modcount = = Expectedmodcount;

1. The loop starts, because Modcount and expectedmodcount are equal, the first loop acquires the object entry

2. After entering the loop body, the Processes.remove (PID) method actually calls the Removenode method of the parent class HashMap, finally ++modcount, and Expectedmodcount does not change 3. Continue the loop, in the NextNode () method, due to modcount! = Expectedmodcount, Report concurrentmodificationexceptionAbnormal! Solution: Single Thread:Use iterators to delete through iterators.

Why do I use iterators to delete without error? Because the iterator has its own encapsulated remove method, the last step is one more action Expectedmodcount = Modcount

Multithreading: can use Copyonwritearraylist,concurrenthasmap and so on The list and map collection classes all have these problems, please use it carefully when coding.

Java concurrentmodificationexception exception causes and workarounds

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.