CopyOnWriteArrayList Snapshot Iteration
Iterate a CopyOnWriteArrayList while updates land: the iterator holds an immutable snapshot, so concurrent modification never throws mid-loop.
Code
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class ListenerRegistry {
public static void main(String[] args) {
List<String> listeners = new CopyOnWriteArrayList<>();
listeners.add("audit");
listeners.add("metrics");
// 迭代器基于创建时刻的数组快照,不反映之后的修改
Iterator<String> snapshot = listeners.iterator();
listeners.add("billing"); // 迭代期间修改,也不会抛 ConcurrentModificationException
while (snapshot.hasNext()) {
System.out.println("snapshot sees: " + snapshot.next());
}
System.out.println("current list: " + listeners);
// 写时复制:每次 add 都复制整个底层数组,读多写少才划算
listeners.remove("audit");
System.out.println("after remove: " + listeners);
}
}How it works
CopyOnWriteArrayList Snapshot Iteration is built around the class ListenerRegistry and the function main.
Repetition is confined to while (snapshot.hasNext()) — the rest of the file is straight-line.
Using it
Output lines are prefixed (snapshot sees:, current list:, after remove:), so each line of output points at the operation responsible for it.
Key statements
listeners.add("billing"); // 迭代期间修改,也不会抛 ConcurrentModificationException
while (snapshot.hasNext()) {
System.out.println("snapshot sees: " + snapshot.next());
}
List<String> listeners = new CopyOnWriteArrayList<>();
Iterator<String> snapshot = listeners.iterator();
Interactive Tools for This Topic
FAQ
- What does CopyOnWriteArrayList Snapshot Iteration print when run?
- No setup needed: run the file and look for labeled lines like `snapshot sees:`, `current list:`, `after remove:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.