According to the Java API documentation [API 2006] for the Iterator.remove()
method:
...
According to the Java API documentation [API 2006] for ConcurrentModificationException
:
...
Reliance on ConcurrentModificationException
is inadequate to prevent undefined behavior resulting from modifying an underlying collection while simultaneously iterating over the collection. The fail-fast behavior may occur only after processing an arbitrary number of elements. In Java Concurrency in Practice [Goetz 2006a], Goetz and colleagues note:
...
This noncompliant code example (based on Sun Developer Network SDN 2011 bug report 6687277) uses the ArrayList
's remove()
method to remove an element from an ArrayList
while iterating over the ArrayList
. The resulting behavior is unspecified.
...
This approach must be implemented correctly to avoid starvation, deadlock, and scalability issues [Goetz 2006a].
Compliant Solution (Deep Copying)
...
Creating deep copies of the list prevents underlying changes in the original list from affecting the iteration in progress. "Since the clone is thread-confined, no other thread can modify it during iteration, eliminating the possibility of ConcurrentModificationException
. (The collection still must be locked during the clone operation itself)" [Goetz 2006a]. However, this approach is often more expensive than other techniques. There is also a risk of operating on stale data, which may affect the correctness of the code.
...
The Apache Harmony bug HARMONY-6236 documents an ArrayList
breaking when given concurrent collections as input.
Bibliography
...
Rule 49: Miscellaneous (MSC) CERT Oracle Coding Standard for Java