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