CKTIS / Java
util.concurrent.CopyOnWriteArrayList: practical reference
util.concurrent.CopyOnWriteArrayList: practical reference: CopyOnWriteArrayList<E> is a thread-safe list that copies its entire backing array on every mutation.
Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime
Syntax
java.util.concurrent.CopyOnWriteArrayListCopyOnWriteArrayList is a thread-safe list that copies its entire backing array on every mutation.
Use it when traversals vastly outnumber rare writes and readers should not lock.
add, set, and remove pay an O(n) copy, while an iterator sees a fixed snapshot and misses later changes.
Iterator mutation methods remove, set, and add are unsupported and no ConcurrentModificationException is thrown; null is allowed and element publication has a happens-before guarantee.
The example exercises the documented element in a small deterministic program and compares exact standard output.
Examples
public class Main {
public static void main(String[] args) throws Exception {
var list = new java.util.concurrent.CopyOnWriteArrayList<>(java.util.List.of(1, 2));
var iterator = list.iterator();
list.add(3);
System.out.println(iterator.next() + iterator.next());
System.out.println(list.size());
}
}
Result
3 3
The example exercises the documented element in a small deterministic program and compares exact standard output.