5 ms·
An example of a deadlock that continues the bank balance analogy: A transfer funds method that does: 1. Lock account A 2. Get balance and check 3. Lock account
by DecoPerson 7y ago
An example of a deadlock that continues the bank balance analogy:
A transfer funds method that does:
1. Lock account A
2. Get balance and check
3. Lock account B
4. Debit account A
5. Credit account B
If the two accounts transfer to each other at the same time, you can get:
1. A->B: Lock account A
2. A->B: Get balance and check
3. B->A: Lock account B
4. B->A: Get balance and check
5. A->B: Lock account B -- deadlock
One solution is to always acquire locks in the same order and release all of them when you fail to obtain one. You can do this in the transfer example by sorting by account ID (so always lock A before B).