Locks, Atomics & Coordination
KOTLIN › JVM Concurrency
The full toolkit for shared mutable state, from immutability through atomics to locks, and the ways locks fail.
Interviewers ask "how would you make this thread-safe" and listen for whether you reach straight for a lock or work down a ladder. Expect to justify atomics over locking for a single value, explain compare-and-set and why it degrades under contention, cap concurrency with a Semaphore, and name the four conditions for deadlock along with which one lock ordering eliminates. Strong answers know that a monitor cannot be held across a suspending call, that Mutex is deliberately not reentrant, and that a read lock cannot be upgraded.
What this covers
- The ladder: immutability, then confinement, then atomics, then a lock, then a specialised lock
- synchronized locks this for an instance method and the Class for a static one, and creates a happens-before edge
- Never lock on a String literal or boxed value: interning can share the monitor with unrelated code
- ReentrantLock adds tryLock with timeout, interruptible acquisition, fairness, and Condition wait sets
- Fairness prevents starvation at a real throughput cost, because barging is what makes unfair locks fast
- Coroutine Semaphore(n) caps how many coroutines are inside a section, which beats limitedParallelism for in-flight requests
- CountDownLatch counts events and is one-shot; CyclicBarrier counts arriving threads and resets
- Compare-and-set is one instruction: check the expected value and write, with nothing able to interleave
- CAS is optimistic, so heavy contention means wasted retries; LongAdder uses per-thread cells instead
- ABA: CAS verifies the current value, not that it never changed, which AtomicStampedReference fixes
- Deadlock needs four conditions; lock ordering eliminates circular wait and tryLock eliminates hold-and-wait
- Deadlock blocks, livelock spins, starvation serves everyone but one; priority inversion is the Android variant
Study this topic
- Locks, Atomics & Coordination explained: the guided lesson
- 17 practice quiz questions
- 16 revision flashcards
- Locks, Atomics & Coordination interview questions and answers