Command Palette

Search for a command to run...

PHASE 5Advanced ~6 min· topic 7 of 11

Topic 5.7

Locks vs Atomics

In one line

The performance/readability trade: when to use synchronized/locks vs CAS atomics.

0/11 · 0%

Think of it like this

Paying with exact change (atomic: one quick, lock-free action) versus asking the cashier to hold your bag while you count your wallet AND pick your items (lock: multiple things need to happen together, so you need to reserve the cashier's attention).

Key ideas

  1. 01

    Atomics: lock-free on the happy path, retry on contention — great for counters, flags, single-field claims.

  2. 02

    Locks: needed for multi-field invariants (two fields must change together) and compound operations.

  3. 03

    Rule: single field → atomic; multi-field transition → lock; entire collection mutation → concurrent collection.

  4. 04

    Contention curve: at low contention CAS wins; under pathological contention locks can win (no retry storms).

  5. 05

    Interview answer format: 'this is a multi-field invariant → I take the write lock'.

Java / Spring map

  • →

    AtomicReference + immutable records = lock-free state machines (compareAndSet whole state object).

Explain without notes

01

Seat 'HELD→BOOKED' touches two fields — why must that be atomic? Which tool?

Practice

01

Rebuild the elevator state change as AtomicReference<State> and compare with the lock version.

Trade-offs

  • ↔

    CAS retries burn CPU; locks burn latency. Measure, don't guess — but in interviews, state the reasoning.

Completion checklist

  • I choose between atomic and lock by counting the fields in the invariant.

Back to phase