Which standard Java collections are remove-safe during iteration?

java

Solution

One such collection is `CopyOnWriteArrayList`. Other collections in the `java.util.concurrent` package share this feature.

The fact that their iterators never throw a `ConcurrentModificationException` is a side-effect of the copy-on-write semantics of this class: every time you modify it, the underlying array will be copied. This is done to allow fast concurrent access to often-read but rarely-modified lists.

The JavaDoc explains it like this (emphasis mine):

The "snapshot" style iterator method uses a reference to the state of the array at the point that the iterator was created. This array never changes during the lifetime of the iterator, so interference is impossible and the iterator is guaranteed not to throw `ConcurrentModificationException`.

In addition to the high costs of updates this implementation has some further drawbacks:

The iterator will not reflect additions, removals, or changes to the list since the iterator was created. Element-changing operations on iterators themselves (`remove`, `set`, and `add`) are not supported. These methods throw `UnsupportedOperationException`.

Note that those collections are not meant to be utility to allow "easy" looping-and-removal, but are specialized collections for use in high-concurrency situations where many threads need concurrent access to data that can still change (but usually changes rarely). Do not simply replace every `ArrayList` with a `CopyOnWriteArrayList`.

Problem

Using `for(Type x:collection){...}` which widely used collection types make removing `x` safe during iteration? And is there a technical term for this to look out for in the JavaDocs? Clarification: I initially only asked about using the for-each syntax `for(Type x:collection){...}`. However a more complete answer would describe this style AND using a normal Iterator-based loop where there are differences... the question is more about which standard Collections allow me to remove elements during iteration, AND how to perform the iteration to allow this.

Original source