Locks, Atomics & Coordination Interview Questions
KOTLIN › JVM Concurrency
What does synchronized do, and what is the coroutine equivalent?
What a strong answer covers: synchronized makes a block mutually exclusive on a monitor object and creates happens-before so changes are visible to the next thread that takes the lock. In coroutines, a blocking lock wastes a thread while waiting, so use Mutex with withLock, which suspends instead of blocking, or confine state to a single thread with limitedParallelism(1).
When would you use AtomicInteger or AtomicReference instead of a lock?
What a strong answer covers: For single-variable updates like counters, flags or swapping a reference, atomics use lock-free compare-and-swap, which is cheaper than a lock under low contention and can't deadlock. When several variables must change together consistently, you need a lock or to wrap them in an immutable object swapped through one AtomicReference.
What is a deadlock, and how do you prevent one?
What a strong answer covers: A deadlock is when two or more threads each hold a lock the other needs, so none proceeds. Prevention: always acquire locks in a consistent global order, hold locks for as little time as possible, never call unknown code (callbacks, listeners) while holding a lock, use tryLock with a timeout, or design to avoid shared mutable state.
Why can't you hold a Kotlin Mutex across a call that re-enters the same Mutex, and how does it differ from ReentrantLock?
What a strong answer covers: Mutex isn't reentrant: a coroutine that calls lock() again while holding it suspends forever, waiting on itself. ReentrantLock and synchronized are reentrant per thread. Coroutines can't use thread-based reentrancy because they move between threads. Design around it: don't call locked functions from inside locked sections, or split public locked functions from private unlocked helpers.
What are compare-and-swap loops, the ABA problem, and contention costs? When would a lock actually outperform atomics?
What a strong answer covers: A CAS loop reads a value, computes a new one, and retries if another thread changed it in between. ABA is when a value changes from A to B and back to A, so CAS succeeds although the state changed; fix with a version stamp (AtomicStampedReference). Under heavy contention, CAS loops waste CPU spinning, and a lock that parks waiting threads, or striping like LongAdder, can perform better.