Pick the fix
transfer(a, b) locks a then b; transfer(b, a) locks b then a. Fix?
Hint 1 of 1
What would stop the cycle forming?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A Lock both accounts in sorted id order in every path
Correct. Same order everywhere means no cycle.
A deadlock needs a cycle: each thread holds one lock and waits for the other's. If every path takes locks in the same global order, such as by account id, no cycle can form.
Why not the others?
- B Add a sleep between the two acquisitions. Changes timing, not the cycle.
- C Use more threads. More contenders, same cycle.
- D Catch exceptions around the second acquire. A blocked acquire raises nothing.