C

Core Java tutorial for beginners

Clean • Professional

CopyOnWriteArraySet in Java – Thread Safety, Examples & Usage

3 minute

CopyOnWriteArraySet in Java

CopyOnWriteArraySet is a thread-safe Set implementation in Java that is based on CopyOnWriteArrayList.

It is part of the java.util.concurrent package and is useful in multi-threaded scenarios where reads are more frequent than writes.


What is CopyOnWriteArraySet?

  • A Set that does not allow duplicates
  • Internally backed by CopyOnWriteArrayList
  • Thread-safe without using explicit synchronization
  • Iterators are fail-safe (do not throw ConcurrentModificationException)
  • Ideal for read-heavy collections

Package

import java.util.concurrent.CopyOnWriteArraySet;

Features of CopyOnWriteArraySet

FeatureDescription
Thread-safeSupports concurrent access without external locks
No duplicatesSet semantics – duplicates are not allowed
Fail-safe iteratorIterators work on a snapshot of the array
Backed byCopyOnWriteArrayList
PerformanceWrites are costly (copying array), reads are very fast
Null elementsAllows one null element

Where CopyOnWriteArraySet Fits in Collection Hierarchy

Iterable
   └── Collection
         └── Set
               └── CopyOnWriteArraySet

Implements:

  • Set<E>
  • Serializable
  • Cloneable

How CopyOnWriteArraySet Works Internally

  • Every mutative operation (add, remove, etc.) creates a new copy of the internal array.
  • Iterators work on a snapshot of the array at the time of iterator creation → no ConcurrentModificationException.
  • Reading operations (contains, size, iteration) are fast and non-blocking.

Constructors

Default Constructor

CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();

Constructor with Collection

List<String> list = Arrays.asList("A", "B", "C");
CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>(list);

Common Methods

MethodDescription
add(E e)Adds element if not present
remove(Object o)Removes element if present
contains(Object o)Checks if element exists
size()Returns number of elements
isEmpty()Checks if set is empty
iterator()Returns fail-safe iterator
clear()Removes all elements
addAll(Collection c)Adds all elements from another collection

Example

import java.util.concurrent.CopyOnWriteArraySet;

public class Main {
    public static void main(String[] args) {
        CopyOnWriteArraySet<String> set = new CopyOnWriteArraySet<>();

        set.add("Apple");
        set.add("Banana");
        set.add("Cherry");
        set.add("Apple"); // Duplicate ignored

        System.out.println("Set: " + set);

        set.remove("Banana");

        System.out.println("After removal: " + set);

        // Iteration
        for (String s : set) {
            System.out.println(s);
        }
    }
}

Output:

Set: [Apple, Banana, Cherry]
After removal: [Apple, Cherry]
Apple
Cherry

When to Use CopyOnWriteArraySet

  • When reads are frequent and writes are rare
  • For event listener lists
  • For cache of read-mostly data
  • When thread-safe iteration without locks is needed

Advantages

  • Thread-safe without explicit locks
  • Fail-safe iterators
  • Fast read operations
  • No duplicates allowed

Disadvantages

  • Expensive write operations (array copy)
  • Not suitable for write-heavy workloads
  • Consumes more memory for large sets

Time Complexity

OperationComplexity
add()O(n) (due to array copy)
remove()O(n)
contains()O(n)
size()O(1)
IterationO(n)

CopyOnWriteArraySet vs HashSet in Java

FeatureCopyOnWriteArraySetHashSet
Thread-safetyThread-safe, internally synchronized (safe for concurrent access)Not thread-safe; external synchronization needed for multi-threading
Underlying StructureBacked by CopyOnWriteArrayListBacked by a HashMap
PerformanceReads are very fast (no locks), writes are expensive (entire array copied on modification)Fast for add, remove, and contains (hash-based)
IterationIterators reflect a snapshot; no ConcurrentModificationExceptionFail-fast iterators; throw ConcurrentModificationException if modified during iteration
Use-caseIdeal for mostly-read, rarely-written scenarios (event listeners, caching)Ideal for general-purpose sets with frequent add/remove operations
Allows nullYes, allows one null elementYes, allows one null element
DuplicatesNo duplicates allowedNo duplicates allowed
MemoryHigher memory usage for writes (copies array on every modification)Memory-efficient for most scenarios

Difference Between CopyOnWriteArraySet & CopyOnWriteArrayList

FeatureCopyOnWriteArraySetCopyOnWriteArrayList
Interface ImplementedImplements Set interfaceImplements List interface
Duplicates AllowedNo duplicates allowed (Set property)Duplicates allowed (List property)
OrderingNo guaranteed order (insertion order maintained due to underlying list)Maintains insertion order
Thread-safetyThread-safe; all mutative operations create a new copyThread-safe; all mutative operations create a new copy
Underlying StructureBacked by CopyOnWriteArrayList internallyBacked by array
Iteration BehaviorIterators reflect a snapshot, safe in concurrent accessIterators reflect a snapshot, safe in concurrent access
Best Use-caseMostly-read sets; where uniqueness is requiredMostly-read lists; duplicates and order matter
PerformanceWrites are expensive (array copied on every add/remove)Writes are expensive (array copied on every add/remove)
Allows nullYes, allows one nullYes, allows multiple nulls

Points to Remember

CopyOnWriteArraySet = Thread-safe Set based on CopyOnWriteArrayList, ideal for read-heavy, low-write multi-threaded applications.

  • Allows fail-safe iteration
  • No duplicates
  • Writes are costly, reads are fast

Article 0 of 0