CopyOnWriteArrayList
35 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)CopyOnWriteArrayList (in java.util.concurrent) is a thread-safe List with an unusual trick: it never changes its array in place. Every write builds a new copy, so readers can loop over the old array with no lock and no ConcurrentModificationException.
Every write copies the array
CopyOnWriteArrayList is a thread-safe list that makes a fresh copy of its array on every change, so reading is fast and never blocked.
Copy-on-write means that add, set and remove copy the whole inner array, change the copy, and then switch the list to the new array in one step. Writers take a lock so that two writes cannot copy at the same time.
Example 1 · Two threads adding notices
import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;
public class CowBasicsDemo { public static void main(String[] args) throws InterruptedException { List<String> notices = new CopyOnWriteArrayList<>(); notices.add("Fee last date: 10 July");
Thread office = new Thread(() -> { for (int i = 1; i <= 500; i++) { notices.add("Office notice " + i); // each add copies the array } }, "office"); Thread hostel = new Thread(() -> { for (int i = 1; i <= 500; i++) { notices.add("Hostel notice " + i); } }, "hostel");
office.start(); hostel.start(); office.join(); hostel.join();
System.out.println("Notices: " + notices.size()); System.out.println("First: " + notices.get(0)); }}Notices: 1001 First: Fee last date: 10 July
What this code does
- Two threads add 500 notices each. Every
addcopies the array under the list's lock, so none is lost and the size is always 1,001. - Reads such as
get(0)take no lock: they read the current array directly.
Example 2 · addIfAbsent: register each device once
import java.util.ArrayList;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;
public class AddIfAbsentDemo { public static void main(String[] args) throws InterruptedException { CopyOnWriteArrayList<String> devices = new CopyOnWriteArrayList<>(); List<Thread> threads = new ArrayList<>();
for (int t = 1; t <= 4; t++) { Thread th = new Thread(() -> { for (int d = 1; d <= 300; d++) { devices.addIfAbsent("device-" + d); // check and add in one atomic step } }, "push-server-" + t); threads.add(th); th.start(); } for (Thread th : threads) { th.join(); }
System.out.println("Registered devices: " + devices.size()); System.out.println("Second addIfAbsent of device-7: " + devices.addIfAbsent("device-7")); }}Registered devices: 300 Second addIfAbsent of device-7: false
What this code does
- Four push servers register the same 300 devices.
addIfAbsentchecks and adds in one atomic step, so each device appears exactly once on every run. - It returns
falsewhen the item is already present, so the last line printsfalse.
Readers (get, size, contains, loops) take no lock at all: they simply read whichever array is current.
Because an array is never changed after it is published, a reader can never see a half-done write. For the same reason, a list that hundreds of threads read and only a few threads change is both safe and fast.
Each single method is atomic, but two calls such as contains then add are still a race. For "add only if missing", use its atomic method addIfAbsent (Example 2), or use CopyOnWriteArraySet, which never keeps duplicates.
Snapshot iterators never throw ConcurrentModificationException
A snapshot iterator loops over the array that existed when the loop started. Later changes go into a new array, so the loop never throws ConcurrentModificationException and never sees them.
When a loop starts, its iterator keeps a reference to the array that is current at that moment. This is a snapshot iterator: it walks that fixed array until the end, whatever other threads (or the loop itself) do to the list meanwhile.
Example 3 · Changing the list during a loop
import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;
public class SnapshotLoopDemo { public static void main(String[] args) { List<String> queue = new CopyOnWriteArrayList<>(List.of("Anil", "Bindu", "Charan"));
for (String name : queue) { // the loop uses the array as it was at the start System.out.println("Serving " + name); if (name.equals("Anil")) { queue.add("Dimple"); // creates a NEW array; this loop never sees it queue.remove("Charan"); } } System.out.println("List now: " + queue); }}Serving Anil Serving Bindu Serving Charan List now: [Anil, Bindu, Dimple]
What this code does
- The loop adds
Dimpleand removesCharanwhile servingAnil, yet it still serves the three names it started with and throws no exception. - The list itself did change, as the last line shows. The loop simply kept walking its own snapshot of the old array.
Example 4 · Iterator remove is not supported
import java.util.Iterator;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;
public class IteratorRemoveDemo { public static void main(String[] args) { List<Integer> fines = new CopyOnWriteArrayList<>(List.of(0, 50, 0, 120));
Iterator<Integer> it = fines.iterator(); try { while (it.hasNext()) { if (it.next() == 0) { it.remove(); // a snapshot cannot be changed } } } catch (UnsupportedOperationException e) { System.out.println("it.remove(): UnsupportedOperationException"); }
fines.removeIf(f -> f == 0); // change the list itself instead System.out.println("Fines left: " + fines); }}it.remove(): UnsupportedOperationException Fines left: [50, 120]
What this code does
- With an
ArrayList,it.remove()is the safe way to remove during a loop. Here it throwsUnsupportedOperationException, because the iterator's snapshot array can never change. fines.removeIf(f -> f == 0)changes the list itself and makes one new copy for the whole operation.
So you can add or remove items during a loop and never get a CME, but the loop does not see those changes (Example 3). A reader sees a consistent picture of one moment, which is often exactly what you want for a display or a notification loop. The snapshot cannot be changed: iterator.remove(), set and add on the iterator throw UnsupportedOperationException (Example 4). Change the list itself, for example with list.remove(x) or list.removeIf(...).
Trace the code
Trace a loop that adds to its own list
Variables
- listeners
- []
Output
(nothing printed yet)Line 5An empty CopyOnWriteArrayList is created.
Listener lists as the ideal use
A listener (also called an observer) is an object that wants to hear about events, such as "order status changed". The object that sends the events keeps a list of listeners and loops over it for every event.
Example 5 · Order status listeners
import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;
interface OrderListener { void onStatus(String orderId, String status);}
class OrderTracker { private final List<OrderListener> listeners = new CopyOnWriteArrayList<>();
void subscribe(OrderListener l) { listeners.add(l); // rare: when a screen opens }
void unsubscribe(OrderListener l) { listeners.remove(l); }
void publish(String orderId, String status) { for (OrderListener l : listeners) { // often: every status change, no lock l.onStatus(orderId, status); } }}
class OneTimeSms implements OrderListener { private final OrderTracker tracker;
OneTimeSms(OrderTracker tracker) { this.tracker = tracker; }
@Override public void onStatus(String orderId, String status) { System.out.println(" SMS: " + orderId + " is " + status + " (SMS alerts now off)"); tracker.unsubscribe(this); // removes itself during the loop }}
public class OrderListenersDemo { public static void main(String[] args) { OrderTracker tracker = new OrderTracker(); tracker.subscribe((id, s) -> System.out.println(" App: " + id + " -> " + s)); tracker.subscribe(new OneTimeSms(tracker)); tracker.subscribe((id, s) -> System.out.println(" Rider map updated for " + id));
System.out.println("Status 1:"); tracker.publish("ORD-1042", "PREPARING"); System.out.println("Status 2:"); tracker.publish("ORD-1042", "OUT FOR DELIVERY"); }}Status 1: App: ORD-1042 -> PREPARING SMS: ORD-1042 is PREPARING (SMS alerts now off) Rider map updated for ORD-1042 Status 2: App: ORD-1042 -> OUT FOR DELIVERY Rider map updated for ORD-1042
What this code does
publishloops over the listeners for every status change with no lock. The one-time SMS listener removes itself in the middle of the loop, and nothing breaks.- The rider-map listener still gets status 1, because the loop uses its snapshot. From status 2 onwards, the SMS listener is gone.
This list is read on every event but changed only when a screen opens or closes, so it is read far more often than it is written. Listeners may even remove themselves while being notified, which would throw a CME with an ArrayList. CopyOnWriteArrayList handles both cases with no locking code at all (Example 5). Other good fits follow the same pattern: a small list of allowed IP addresses, enabled feature flags, or configured payment gateways, which almost never change but are checked on every request.
Why it is bad for frequent writes
Every write copies the whole array, so one add to a list of n items costs about n steps instead of about 1.
Example 6 · The cost of copying on every add
import java.util.ArrayList;import java.util.Collections;import java.util.List;import java.util.concurrent.CopyOnWriteArrayList;
public class WriteCostDemo { static long timeAdds(List<Integer> list, int count) { long start = System.nanoTime(); for (int i = 0; i < count; i++) { list.add(i); } return (System.nanoTime() - start) / 1_000_000; }
public static void main(String[] args) { int n = 30_000; List<Integer> synced = Collections.synchronizedList(new ArrayList<>()); List<Integer> cow = new CopyOnWriteArrayList<>();
System.out.println("Adding " + n + " items one by one:"); System.out.println(" synchronizedList: " + timeAdds(synced, n) + " ms"); System.out.println(" CopyOnWriteArrayList: " + timeAdds(cow, n) + " ms");
// Add number i copies the i items already there: 0 + 1 + 2 + ... + (n - 1). long copies = (long) n * (n - 1) / 2; System.out.println("Items copied by CopyOnWriteArrayList: " + copies); }}Adding 30000 items one by one: synchronizedList: 3 ms CopyOnWriteArrayList: 1435 ms Items copied by CopyOnWriteArrayList: 449985000
What this code does
- Adding 30,000 items to a synchronized list takes a few milliseconds. The same adds on a
CopyOnWriteArrayListtake over a second, because each add copies everything added before it. - The timings differ from machine to machine and run to run; the number of copied items is the same every time.
Adding n items one by one copies 0 + 1 + 2 + … + (n − 1) items, which is about n²/2. Example 6 adds 30,000 items: that is about 450 million copied items.
Each copy also creates a new array for the garbage collector to clean up later, and writers still take turns on one lock. For a list that changes often, such as an event log, a shopping cart or a work queue, use a synchronized list, a ConcurrentHashMap or a queue instead.
- Good: listeners, settings, small lists read on every request.
- Bad: logs, counters, queues, any list with frequent
addorremove. - Tip:
addAll(collection)copies once for the whole batch, not once per item.
Next step
Check your understanding
12 quick questions