CopyOnWriteArraySet in Java: Introduction, Principles, API, and Example
This article introduces Java's CopyOnWriteArraySet, explains its thread‑safe design and underlying data structure, lists its core methods, and provides a complete example comparing its behavior with HashSet under concurrent modifications, illustrating when to use this collection.
The article presents a comprehensive guide to Java's CopyOnWriteArraySet, covering its purpose, internal implementation, API methods, and practical usage examples.
Contents include:
CopyOnWriteArraySet introduction
Principles and data structure
Function (method) list
Example code comparing with
HashSet CopyOnWriteArraySetis a thread‑safe, unordered set built on top of CopyOnWriteArrayList. It is ideal for small collections where read operations vastly outnumber writes, because each mutating operation creates a fresh copy of the underlying array.
Key characteristics:
Suitable for scenarios with a small set size and many read operations.
Provides thread safety without external synchronization.
Mutating operations (add, remove, etc.) are costly due to array copying.
Iterators operate on an immutable snapshot, offering fast, conflict‑free traversal.
The set inherits from AbstractSet and internally holds a CopyOnWriteArrayList. Duplicate elements are prevented by the set semantics, while the list allows duplicates; therefore CopyOnWriteArraySet adds elements only when they are absent.
Function list (selected methods):
CopyOnWriteArraySet()
CopyOnWriteArraySet(Collection<? extends E> c)
boolean add(E e)
boolean addAll(Collection<? extends E> c)
void clear()
boolean contains(Object o)
boolean containsAll(Collection<?> c)
boolean equals(Object o)
boolean isEmpty()
Iterator<E> iterator()
boolean remove(Object o)
boolean removeAll(Collection<?> c)
boolean retainAll(Collection<?> c)
int size()
Object[] toArray()
<T> T[] toArray(T[] a)Example program: The following code creates two threads that concurrently add elements to a CopyOnWriteArraySet and iterate over it. When the same code uses a plain HashSet, a ConcurrentModificationException occurs.
import java.util.*;
import java.util.concurrent.*;
public class CopyOnWriteArraySetTest1 {
private static Set<String> set = new CopyOnWriteArraySet<>();
public static void main(String[] args) {
new MyThread("ta").start();
new MyThread("tb").start();
}
private static void printAll() {
Iterator<String> iter = set.iterator();
while (iter.hasNext()) {
System.out.print(iter.next() + ", ");
}
System.out.println();
}
private static class MyThread extends Thread {
MyThread(String name) { super(name); }
@Override
public void run() {
for (int i = 0; i < 10; i++) {
String val = getName() + "-" + (i % 6);
set.add(val);
printAll();
}
}
}
}Sample output demonstrates that the set never contains duplicate entries and that iteration proceeds safely without throwing exceptions.
Overall, the guide helps developers understand when to choose CopyOnWriteArraySet for thread‑safe collections and provides ready‑to‑run source code for experimentation.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Big Data Technology & Architecture
Wang Zhiwu, a big data expert, dedicated to sharing big data technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
