ConcurrentModificationException : This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.<
But it runs OK. No exception is thrown. Why?
Simply because that concurrent modification is permissible.
The description of the exception says this:
"This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible."
The clear implication is that are (or may be) permissible concurrent modifications. And in fact for the standard Java non-concurrent collection classes, concurrent modifications are permitted ... provided that they don't happen during an iteration.
The reasoning behind this is that for the non-concurrent collections, modification while iterating is fundamentally unsafe and unpredictable. Even if you were to synchronize correctly (and that isn't easy1), the result would still be unpredictable. The "fail-fast" checks for concurrent modifications were included in the regular collection classes because this was a common source of Heisenbugs in multi-threaded applications that used the Java 1.1 collection classes.
1- For instance, the "synchronizedXxx" wrapper classes don't, and can't synchronize with iterators. The problem is that iteration involves alternating calls to next()
and hasNext()
, and the only way to do a pair of method calls while excluding other threads is to use external synchronization. The wrapper approach isn't practical in Java.