Why does my sample not throw a ConcurrentModificationException

I wrote this example following the ConcurrentModificationException test:

 public class Person { String name; public Person(String name) { this.name = name; } } public static void main(String[] args) { List<Person> l = new ArrayList<Person>(); l.add(new Person("a")); l.add(new Person("b")); l.add(new Person("c")); int i = 0; for(Person s : l) { if(s.name.equals("b")) l.remove(i); i++; } for(Person s : l) System.out.println(s.name); } 

When I executed the above main method, ConcurrentModificationException will not be thrown, and the output console will output the following result:

 a c 

As far as I know about this problem, when in the loop for the list, when changing the list, you should throw a ConcurrentModificationException . But why doesn’t this happen in my example?

+5
source share
1 answer

There is no guarantee that structural changes to the list will ConcurrentModificationException .

From the documentation :

Please note that fault tolerance cannot be guaranteed, since it is generally not possible to make any serious warranties if there is an unsynchronized parallel modification. Failsafe operations throw a ConcurrentModificationException with maximum efficiency. Therefore, it would be wrong to write a program that depends on this exception for its correctness: ConcurrentModificationException should be used only to detect errors.

In this particular case, you are “happy” (or “unhappy” depending on how you see it). Structural changes go unnoticed because a cycle exists before another modification check is performed.

See the answers in dup for a detailed explanation:

+1
source

All Articles