Video in progress

How do you store a set of rules that is read hundreds of thousands of times per second but rarely updated, across threads?

An immutable snapshot plus a single volatile reference (or an AtomicReference): readers take the current snapshot without a lock, and the writer builds a complete new copy and swaps the reference in one step. Reads are nearly free, and consistency is guaranteed at the level of the whole snapshot.

📖 Answer

A lock-based approach, even ReadWriteLock, writes to shared state on every read, which is noticeable on a very hot path. With the snapshot approach the reader writes nothing:

public final class PricingRules {
    private record Snapshot(Map<String, BigDecimal> rates, Set<String> blocked, long version) { }

    private volatile Snapshot current = new Snapshot(Map.of(), Set.of(), 0);

    public BigDecimal rate(String sku) {
        Snapshot s = current;                     // a single volatile read
        return s.blocked().contains(sku) ? null : s.rates().get(sku);
    }

    public synchronized void reload(Map<String, BigDecimal> rates, Set<String> blocked) {
        current = new Snapshot(Map.copyOf(rates), Set.copyOf(blocked), current.version() + 1);
    }
}

Important details:

  • the reader takes the snapshot once into a local variable. If it reads current twice, it can mix two different versions;
  • everything inside the snapshot must be truly immutable (Map.copyOf, a record). If a plain HashMap is left inside and someone changes it later, the whole idea breaks;
  • if there are several writers, make reload synchronized or use AtomicReference.updateAndGet, otherwise one of two parallel updates is lost.

Where it breaks down:

  • updates are frequent and the snapshot is large: copying the whole set on every change raises the cost of allocation and GC. Then going back to ConcurrentHashMap is better;
  • a reader runs for a long time and always needs the "latest" value: it keeps going with the old snapshot it took at the start. That's usually acceptable, but agree on it with the business.

Bonus: with a version field it's easy to show in logs and metrics which rule set was used, and a rollback is just putting the old snapshot back.