Understanding CopyOnWriteArrayList: Introduction, Principles, API, and Source‑Code Analysis

This article introduces Java's CopyOnWriteArrayList, explains its dynamic‑array and thread‑safety mechanisms, lists the most important methods, provides detailed source‑code walkthroughs for constructors, add, get, remove and iterator implementations, and demonstrates its behavior with a multithreaded example compared to ArrayList.

Big Data Technology & Architecture
Big Data Technology & Architecture
Big Data Technology & Architecture
Understanding CopyOnWriteArrayList: Introduction, Principles, API, and Source‑Code Analysis

CopyOnWriteArrayList is a thread‑safe variant of ArrayList that internally uses a volatile array and a copy‑on‑write strategy, making it ideal for scenarios where reads vastly outnumber writes.

Key characteristics :

Best suited for small lists with many read operations and few modifications.

All mutating operations (add, set, remove, etc.) create a new copy of the underlying array, which incurs high write cost but provides fast, lock‑free reads.

Iterators operate on a snapshot of the array, never throwing ConcurrentModificationException and not supporting element removal or modification.

Dynamic‑array mechanism : The class maintains a volatile transient Object[] array. When an element is added, a new array is created with Arrays.copyOf, the element is placed at the end, and the new array is assigned to the volatile field, guaranteeing visibility across threads.

Thread‑safety mechanism : Mutating methods acquire an exclusive ReentrantLock lock before copying and updating the array, ensuring only one thread modifies the structure at a time.

Important API methods (excerpt):

public CopyOnWriteArrayList() { setArray(new Object[0]); }
public CopyOnWriteArrayList(Collection<? extends E> c) { ... setArray(elements); }
public CopyOnWriteArrayList(E[] toCopyIn) { setArray(Arrays.copyOf(toCopyIn, toCopyIn.length, Object[].class)); }

private volatile transient Object[] array;
final Object[] getArray() { return array; }
final void setArray(Object[] a) { array = a; }

public boolean add(E e) { lock.lock(); try { Object[] elements = getArray(); int len = elements.length; Object[] newElements = Arrays.copyOf(elements, len + 1); newElements[len] = e; setArray(newElements); return true; } finally { lock.unlock(); } }

public E get(int index) { return (E) getArray()[index]; }

public E remove(int index) { lock.lock(); try { Object[] elements = getArray(); int len = elements.length; E oldValue = (E) elements[index]; int numMoved = len - index - 1; if (numMoved == 0) setArray(Arrays.copyOf(elements, len - 1)); else { Object[] newElements = new Object[len - 1]; System.arraycopy(elements, 0, newElements, 0, index); System.arraycopy(elements, index + 1, newElements, index, numMoved); setArray(newElements); } return oldValue; } finally { lock.unlock(); } }

public Iterator<E> iterator() { return new COWIterator<E>(getArray(), 0); }

private static class COWIterator<E> implements ListIterator<E> { private final Object[] snapshot; private int cursor; /* hasNext, next, hasPrevious, previous, etc. */ }

Example usage : The article provides a multithreaded program that creates two threads, each adding elements to a shared CopyOnWriteArrayList and printing the list via an iterator. The output shows interleaved values without throwing ConcurrentModificationException. Replacing the list with a plain ArrayList would cause that exception.

Overall, the article offers a comprehensive guide to the design, implementation, and practical usage of CopyOnWriteArrayList in concurrent Java applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaconcurrencyCollectionsCopyOnWriteArrayListThreadSafety
Big Data Technology & Architecture
Written by

Big Data Technology & Architecture

Wang Zhiwu, a big data expert, dedicated to sharing big data technology.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.