11 January 2021

DeadLock

  • Deadlock describes a situation where two more threads are blocked because of waiting for each other forever. 

  • When deadlock occurs, the program hangs forever and the only thing you can do is to kill the program

  • Ex
    • Thread 1 tries to transfer 150 from account 1 to account 2
    • Thread 2 tries to transfer 170 from account 3 to account 1
  • Account 1 has only 100 in balance so thread 1 has to wait for other threads to deposit more funds to this account. Similarly, thread 2 also has to wait because account 3 doesn’t have sufficient fund. Other threads may add funds to accounts 1 and 3, but if all threads are trying to transfer an amount greater than the account’s balance, they are waiting for each other forever. Hence deadlock occurs.

So how to avoid deadlock?

  • Java doesn’t have anything to escape deadlock state when it occurs, so you have to design your program to avoid deadlock situation.
  • Avoid acquiring more than one lock at a time. If not, make sure that you acquire multiple locks in consistent order. 

No comments:

Post a Comment

Most views on this month