Algorithms

Copy-on-Write Collections

๐Ÿ“‹ Quick Reference

PropertyValue
TypeThread-safe collections via copy-on-write
ReadO(1) - no locking
WriteO(n) - copies entire array
IterationSafe, snapshot at iterator creation
Best ForRead-heavy, rare writes, event listeners
One-liner: Thread-safe collections where writes copy the entire backing array - perfect for read-heavy workloads.

๐ŸŽฎ Interactive Visualizer

Watch how Copy-on-Write handles concurrent reads and writes:

Loading visualizer...
Try these operations:
  1. See multiple readers access simultaneously (no blocking)
  2. Watch a write operation create a new copy
  3. Observe iterators using the old snapshot
  4. Notice: readers never blocked, even during writes

๐Ÿ”ง Key Operations

CopyOnWriteArrayList

JAVA(24 lines)
Code
Loading syntax highlighter...

CopyOnWriteArraySet

JAVA(10 lines)
Code
Loading syntax highlighter...

๐Ÿ“Š Complexity Analysis

OperationCopyOnWriteArrayListCopyOnWriteArraySet
get(i)O(1)N/A
containsO(n)O(n)
addO(n)O(n)
removeO(n)O(n)
iterator()O(1)O(1)
IterationO(n)O(n)

How Copy-on-Write Works

Initial state:
reference โ†’ [A, B, C, D]

Write operation (add "E"):
1. Create new array: [A, B, C, D, E]
2. Copy existing elements
3. Add new element
4. Atomically swap reference

reference โ†’ [A, B, C, D, E]  (new array)
            [A, B, C, D]     (old array, still used by existing iterators)

Existing iterators continue using old array (snapshot)
New iterators use new array

โœ… When to Use Copy-on-Write

Good Use Cases

  • Event listeners - listener list rarely changes, iterated often
  • Configuration - read constantly, updated rarely
  • Observer pattern - notify many observers, add/remove rare
  • Snapshot iteration - need consistent view during traversal
  • Read-heavy workloads - writes are 1% or less of operations

Avoid When

  • Write-heavy - each write copies entire array
  • Large collections - copy cost too high
  • Memory constrained - maintains old copies until iterators complete
  • Need O(1) contains - use ConcurrentHashMap.newKeySet() instead

๐Ÿ”„ Copy-on-Write vs Alternatives

FeatureCopyOnWriteArrayListsynchronizedListConcurrentLinkedQueue
IterationSafe (snapshot)Needs external syncSafe (weakly consistent)
Read performanceExcellentGoodGood
Write performancePoor (O(n))Good (O(1))Good (O(1))
MemoryHigher (copies)NormalNormal
Best forRead-heavyModerate mixQueue operations
JAVA(8 lines)
Code
Loading syntax highlighter...

๐Ÿงฉ Common Patterns

Event Listener Management

JAVA(20 lines)
Code
Loading syntax highlighter...

Configuration Registry

JAVA(15 lines)
Code
Loading syntax highlighter...

Observer Pattern

JAVA(14 lines)
Code
Loading syntax highlighter...

โš ๏ธ Common Pitfalls

1. Using for Write-Heavy Workloads

JAVA(8 lines)
Code
Loading syntax highlighter...

2. Expecting CopyOnWriteArraySet O(1) Contains

JAVA(6 lines)
Code
Loading syntax highlighter...

3. Large Collections

JAVA(6 lines)
Code
Loading syntax highlighter...

4. Modifying During Iteration

JAVA(16 lines)
Code
Loading syntax highlighter...

๐ŸŽค Interview Tips

Q: When would you use CopyOnWriteArrayList?
"

When you have many more reads than writes, especially for things like event listeners or configuration. Writes are expensive (O(n)) but reads are lock-free and iteration is always safe.

Q: How does CopyOnWriteArrayList achieve thread safety?
"

Every mutative operation (add, set, remove) creates a fresh copy of the underlying array. The reference is then atomically swapped. Reads see a consistent snapshot without locking.

Q: Why doesn't iterator support remove()?
"

The iterator works on a snapshot of the array at creation time. The current array may have changed since then, so the iterator can't know which element to remove from the current array.

Q: CopyOnWriteArraySet vs ConcurrentHashMap.newKeySet()?
"

CopyOnWriteArraySet has O(n) contains (linear search) and O(n) writes. ConcurrentHashMap.newKeySet() has O(1) contains and O(1) writes. Use COW only if you need snapshot iteration or very small sets.


๐Ÿ“š Series Navigation


Visualizer: CopyOnWrite from @tomaszjarosz/react-visualizers