CopyOnWriteArrayList

What is CopyOnWriteArrayList?

It is a thread safe variant of ArrayList. It provides thread-safety by creating new arraylist on all update(get, set & so on) operations.

Do you mean CopyOnWriteArrayList is immutable?

No. Though it imitates the behavior immutable classes of creating new underlying arraylist at every update, But, unlike immutable object, it does not return the new object, but update the reference of the underlying arraylist. This makes all these methods ATOMIC. But please understand, when we say CopyOnWriteArrayList is thread-safe, thus would never mean that compound operations on CopyOnWriteArrayList are thread - safe. Read for more details.

CopyOnWriteArrayList should be very expensive?

Yes it is. This is recommended mainly performing read-intensive operations.

Is it (its iterator) fail safe?

Yes. CopyOnWriteArrayList creates a new copy when a (new instance of)iterator is requested. Javadoc says: 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.

How does iterator's remove work in that case?

It does not work. It is the next statement of Javadoc: 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.