Sweaty Imposter

Immutable / Copy-On-Write

TechniqueConcurrencySeniorStaffUpdated
Never mutate a shared object; on write, copy it and atomically swap the reference. Readers are entirely lock-free.

When to Use Immutable / Copy-On-Write

Heavily-read, rarely-written shared state: routing tables, config snapshots, listener lists. Writes get expensive (full copy), so it loses if writes are frequent.

In Practice

Java's CopyOnWriteArrayList (used for listener registries in Swing / Spring), String, persistent collections in Clojure / Scala. The Linux kernel's RCU is a related pattern.

Sketch

Java

private volatile Map<String, Route> routes = Map.of();

public Route lookup(String k) {
    return routes.get(k);                     // lock-free read
}

public synchronized void addRoute(String k, Route r) {
    Map<String, Route> next = new HashMap<>(routes);
    next.put(k, r);
    routes = Map.copyOf(next);                // atomic publish
}

How Immutable / Copy-On-Write Comes Up in Interviews

Scenario

Your gateway routes requests via a 50,000-entry routing table that all worker threads read on every request. The table is rebuilt from ZooKeeper every few minutes. Reads must never block; rebuild can be expensive. Which pattern?

Copy-on-write: build the new table off to the side, then atomically swap a volatile reference. Readers are 100% lock-free and always see a consistent snapshot. An rwlock still touches a lock on every read; thread-local defeats the global-truth requirement.