Topic 5.7
Locks vs Atomics
In one line
The performance/readability trade: when to use synchronized/locks vs CAS atomics.
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
- 01
Atomics: lock-free on the happy path, retry on contention — great for counters, flags, single-field claims.
- 02
Locks: needed for multi-field invariants (two fields must change together) and compound operations.
- 03
Rule: single field → atomic; multi-field transition → lock; entire collection mutation → concurrent collection.
- 04
Contention curve: at low contention CAS wins; under pathological contention locks can win (no retry storms).
- 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
Seat 'HELD→BOOKED' touches two fields — why must that be atomic? Which tool?
Practice
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.