Video in progress

In a multi-threaded, high-load system, how do you design objects: shared mutable state, immutable objects, or a "single owner" model?

The default is immutable objects and giving the state to a single owner (thread confinement, actor/queue). Shared mutable state only when necessary, as small as possible and encapsulated inside one class, with concurrent collections or an explicit lock.

📖 Answer

Encapsulation takes on a new meaning in concurrency: a class has to hide not only the data but the synchronization policy. If the caller has to know "first take the lock, then call", encapsulation is broken.

Three strategies:

  1. Immutable + swap. Configuration, a price table, routing rules: create a whole new object and swap it in through a single volatile/AtomicReference. Readers work without locks.
public final class RatesHolder {
    private final AtomicReference<Rates> current = new AtomicReference<>(Rates.empty());
    public Rates get() { return current.get(); }          // no lock
    public void reload(Rates fresh) { current.set(fresh); } // atomic swap
}
  1. Thread confinement / a single owner. Only one thread changes the state, and the others send it messages (a queue, Kafka by partition key, an actor). For things like an account balance: all operations of one account go to one partition, giving order and consistency without locks.

  2. Encapsulated shared state. ConcurrentHashMap.compute, LongAdder, ReentrantLock. The rule: the lock lives in the same class as the field, and no outside code (callbacks, I/O) is called inside a lock, otherwise you get deadlocks and latency spikes.

Mistakes I often see in prod:

  • a getter returns a mutable internal collection, and another thread changes it without synchronization;
  • "check-then-act" with two separate thread-safe calls: if (!map.containsKey(k)) map.put(k, v) is not atomic;
  • storing request state in a field of a Spring singleton bean.

Virtual threads (Java 21) don't change these design rules, but blocking I/O inside a synchronized block can pin the carrier thread (JDK 24 removed this limitation for synchronized; pinning still happens in native code and class initialization). On 21, prefer ReentrantLock where there are long waits.