Top 4 Lock ordering Interview Questions
Browse 4 real-world technical and behavioral interview questions about Lock ordering. Review scenarios, edge cases, and architectural best practices.
Build a digital wallet with transfers where a balance can never go negative, even when many transfers run at the same moment.
A digital wallet stays non-negative only if the balance check and the debit happen in one critical section. Lock both wallets in a fixed order by id so concurrent transfers cannot deadlock, record every movement as a pair of entries, and make each transfer idempotent on a client key so a retry cannot pay twice.
State the four conditions for deadlock, then show me how you would stop a real program from deadlocking.
Deadlock needs all four Coffman conditions at once: mutual exclusion, hold and wait, no preemption and circular wait. Breaking any one prevents it, and the practical choice is usually circular wait, by making every thread take locks in one global order.
One global lock makes your reservation system correct and slow. How do you split it without deadlocking?
Shrink the critical section first, then replace the global lock with lock striping, a fixed array of locks keyed by resource hash. Lock ordering by ascending stripe index rules out deadlock for multi-resource bookings, tryLock bounds waiting, and invariants the old lock covered by accident each need an owner.
An operation in this code takes two locks and it deadlocks every few weeks. How would you design the locking so that cannot happen?
A deadlock is a cycle in the wait-for graph, so the design goal is a graph that cannot contain one: stop holding two locks where you can, impose one total order on acquisition everywhere you cannot, and never call unknown code while holding a lock.