Top 5 Locking Interview Questions
Browse 5 real-world technical and behavioral interview questions about Locking. Review scenarios, edge cases, and architectural best practices.
Two users click "book" on the last seat in your in-memory booking class at the same moment. Where does the lock go?
The bug is a check-then-act race condition: both threads see the seat free before either marks it taken. The lock must cover the check and the write together, scoped to one show so unrelated shows never wait, and released before payment, with a timed hold standing in for the seat while the user pays.
Two doctors can go off call only if at least one remains. Both check the rule at the same moment, both see two doctors on call, and both go off call. What isolation problem is this, and what actually fixes it?
This is write skew: two transactions read the same set, each writes a different row, and the pair commits a state neither would have produced alone. No row-level constraint can catch it because the invariant is a property of the set, so the fix is either serializable isolation, a lock on something both transactions must touch, or remodelling the invariant onto a single row.
You are getting a handful of deadlock errors an hour under load. How do you find the cause, and how do you stop them?
A deadlock is a cycle in the wait-for graph, so read the engine's own report to get both statements and the locks each held. Nearly all of them come from two code paths taking the same rows in different orders; impose one order, shorten transactions, and retry, because a deadlock is always safe to retry.
How would you design a thread-safe component, and why is adding synchronized to every method not a design?
Thread-safe component design starts by assigning every field a policy: confined, immutable or guarded by a named lock. Method-level synchronization is not enough because atomic methods do not compose into atomic workflows.
Every call you make is on a ConcurrentHashMap, and you still lost an update. How does a thread-safe collection get raced?
Thread safety composes per operation, not across operations. A get followed by a put is two atomic steps with a legal interleaving between them. You close the window by making the whole compound action one operation, such as compute or merge, or by holding a single lock across both steps.