Do not perform the remove/add operation of elements in the Foreach loop. The remove element uses the Iterator method, which requires a lock on the Iterator object if the concurrency operation.
Positive example: iterator<string> Iterator = List.iterator ();
while (Iterator.hasnext ()) {
String item = Iterator.next ();
If (delete element's condition) {
Iterator.remove ();
}
}
Counter example: list<string> List = new arraylist<string> ();
List.add ("1");
List.add ("2");
for (String item:list) {
if ("1". Equals (item)) {
List.remove (item);
}
}
Note: The above code implementation results will certainly surprise everyone, then try to replace "1" with "2", will be the same result.
The root cause is that Expectedmodcount and modcount they are unequal, because of the execution of the ArrayList in the Remove (), modcount in each cycle value will change, and Expectedmodcount did not happen, An exception is thrown when the Checkforcomodification () method is executed.