1

Why

List list = new ArrayList();
    list.add("1");
    list.add("2");
    list.add("3");
    list.stream().forEach(
            s->{
                System.out.println(s);
                list.add(s+"add");
            }
    );

Throws ConcurrentModificationException only after all output:

1
2
3

java.util.ConcurrentModificationException
    at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1661)

? It seems it should be done after 1, isn't it?

J.J. Beam
  • 2,054
  • 1
  • 15
  • 33
  • 3
    As [the documentation](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/ArrayList.html) says: “*Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness*” Performing the check for modifications before and after each element’s processing would impose a performance penalty for every correct program. That’s just a trade-off. – Holger Apr 25 '22 at 13:38

0 Answers0