What is Deadlock and how to avoid it?

Saurav Singh
2 min readNov 12, 2018

--

Deadlock is a scenario where a set of processes is blocked because each process has acquired a lock on a particular resource and is waiting for another resource locked by some other process.

Let me give you an example:

Suppose process1 is making a transaction from one account (R1) to another account (R2), and for that, it will try to acquire a lock on resource R1 and R2.

At the same time, process2 is trying to transfer funds from one account (R2) to another account (R1), and for that, it will try to acquire a lock on resource R2 and R1.

In this scenario, process1 will acquire the lock on resource R1, and process2 will acquire the lock on resource R2, and they will keep on waiting for each other to release the resource.

E.g. Process1 will keep on waiting to acquire a lock on resource R2, which is locked by process2 and process2 will keep on waiting to acquire a lock on resource R1 which is locked by process1 and ends up in deadlock.

Process 1 — Transaction:

let [[accountR1]] = dbConn.execute('Select account_nr, balance FROM balances WHERE account_nr = ? FOR UPDATE', [accountR1]);let [[accountR2]] = dbConn.execute('Select account_nr, balance FROM balances WHERE account_nr = ? FOR UPDATE', [accountR2]);

Process 2- Transaction:

let [[accountR2]] = dbConn.execute('Select account_nr, balance FROM balances WHERE account_nr = ? FOR UPDATE', [accountR2]);let [[accountR1]] = dbConn.execute('Select account_nr, balance FROM balances WHERE account_nr = ? FOR UPDATE', [accountR1]);

How to avoid Deadlock?

In order to avoid deadlock, you have to acquire a lock in the fixed order.

Let me explain by resolving the above deadlock.

If process1 gets the lock on resource R1 and then R2, at the same time, process2 also tries to get the lock on resources in the same order as process1, i.e. On resource R1 and then R2 instead of R2 and then R1.

In this case, process2 has to wait for process1 to finish the transaction.

Once process1 commits the transaction successfully, it will release the locks on the resources; therefore process 2 will get the required resources in order to complete the transaction successfully without getting into the deadlock.

Therefore, please make sure you acquire the lock in the fixed order throughout your application.

I hope this gives you a basic understanding of what Deadlock is, and how to avoid it. Stay tuned for further updates on related topics.

Thank you for reading!

Feedback and thoughts are always welcome in the comments section.

--

--