Deadlock

  • Eclipse: Oxygen
  • Java: 1.8

The deadlock is a condition in which the resources cannot be allocated to two or more threads in current resources requirement, which leads to a state of a halt as the resources cannot be released nor can be acquired therefore this brings the processing to a complete halt. So this situation is studied with the help of threads and locks.

Here is a simple diagram of the Deadlock condition.

In the following program, we have created two threads, thread1 and thread2. In thread2 synchronized block had a lock on object lock2 and in thread1 synchronized block had a lock on object lock1.

‘thread1’ prints “Inside thread1 on lock 1” and ‘thread2’ prints “Inside thread2 on lock 2”. ‘thread1’ tries to acquire the lock on object lock2 but as it is already holed by thread1.

Same happens with thread2. It tries to acquire the lock on object lock1 but it is already holed by thread1, so it waits till it becomes free.  Hence, both threads are in a wait state, waiting for each other to release locks. But none of them is ready to release the lock. This intersection causes the deadlock to occur.

Output

Inside thread1 on lock 1

Inside thread2 on lock 2

Contributed by: Poonam Tomar


Full stack Java Developer

   Buy me a coffee!

 

PayTM QR (INDIA)

Download file

Leave a Reply

avatar
  Subscribe  
Notify of
Close Menu