What is deadlock in java?

A lock occurs when multiple processes try to access the same resource at the same time. A deadlock occurs when the waiting process is still holding on to another resource that the first needs before it can finish. A Java multithreaded program may suffer from the deadlock condition because the synchronized keyword causes the executing thread to block while waiting for the lock, or monitor , associated with the specified object.

Deadlock condition

Resource1 and resource2 are used by Thread1 and Thread2

  1. Thread1 starts to use Resource1
  2. Thread1 and Thread2 try to start using resource2
  3. Thread2 'wins' and gets resource2 first
  4. now Thread2 needs to use Resource1
  5. Resource1 is already locked by Thread1, which is waiting for Thread2

The above situation create deadlock because :

  1. Thread 1 locks Resource1, waits for resource2
  2. Thread 2 locks resource2, waits for Resource1

The best way to avoid deadlocks are:

  1. avoid having locks (if possible)
  2. avoid having more than one lock
  3. always take the locks in the same order
class BankAccount { double currentBalance; void withdrawAmount(double amt){ currentBalance -= amt; } void depositAmount(double amt){ currentBalance += amt; } void transfer(Account from, Account to, double amt){ sync(from); sync(to); from.withdrawAmount(amount); to.depositAmount(amount); release(to); release(from); } }
If two threads which attempt to execute method transfer(a, b) and transfer(b, a) at the same time, then a deadlock is going to occur because they try to acquire the resources in reverse order.