14.16. Deadlock

Deadlock

  • Eclipse: Oxygen
  • Java: 1.8

The deadlock is a condition in which the resources cannot be allocated to two or more threads in the 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.

The 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

Contributed by: Poonam Tomar

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
B R Rachana
B R Rachana
1 year ago

‘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(it must be thread2 right?)