Fast-fail - an exception occurs only when adding an item not when deleting

Fast-Fail : this means that if they discover that the collection has changed since the start of the iteration, they throw an unchecked ConcurrentModificationException .

I wrote a test case to demonstrate this:

  String hi = "Hi"; list.add(hi); list.add("Buy"); System.out.println("list before: " + list); for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { String string = iterator.next(); list.add("Good"); } 

output:

 list before: [Hi, Buy] Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:859) at java.util.ArrayList$Itr.next(ArrayList.java:831) at thread.CollectionTest.main(CollectionTest.java:19) 

which is expected. However, when an item is deleted, an exception is not thrown:

  List<String> list = new ArrayList<>(); String hi = "Hi"; list.add(hi); list.add("Buy"); System.out.println("list before: " + list); for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { String string = iterator.next(); list.remove(hi); } 

Output:

 list before: [Hi, Buy] list after: [Buy] 

Why? in both cases the list has been changed.

+6
source share
2 answers

The fact is that it does not execute hasNext() to change, but next() . In the delete script, you suppress the next call, which will call because there is no next element.

If you had 3 elements at the beginning, deleting one will cause hasNext be "true". Then the next next will throw the expected exception.

The JavaDoc states that the "fault tolerant" functionality works on the basis of the "best efforts" and that it should be used only to detect errors, and not in reality, depending on the fact that the program behaves correctly. Obviously due to side effects like this.

+1
source

ConcurrentModificationException will throw, you can make some changes to the list during iteration.

After making changes to the list during iteration, if you try to access the next () or remove () using an iterator, then it checks modCount and expectedModCount, and the count does not match, and then throws a ConcurrentModificationException .

 final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } 
0
source

All Articles