Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deadlocks using wait and notify

Tags:

java

deadlock

I am trying to understand how deadlocks are created. I've understood that by using two threads on two synchronized methods, a deadlock can be created. Went through many examples from the net.

Can a deadlock be created with wait and notify? Every time a thread is on wait, it will be notified. So how does this end up in a deadlock?

Illustration of an example will be helpful.

like image 702
hakuna12 Avatar asked Nov 11 '13 14:11

hakuna12


Video Answer


2 Answers

Deadlock is caused when two threads try to obtain the same, multiple locks in different order:

    // T1
    synchronized (A) {
      synchronized (B) {
        // ...
      }
    }

    // T2
    synchronized (B) {
      synchronized (A) {
        // ...
      }

}

The only way to prevent deadlocks is to make sure that all threads obtain locks in the same order--either they all do A then B, or they all do B then A.

If you don't have multiple locks, then you don't have a deadlock. However, you can get thread starvation or other things that may look similar to deadlock.

like image 144
constantlearner Avatar answered Sep 28 '22 10:09

constantlearner


Say thread 1 enters a synchronized block on method A and then waits. Thread 2 then attempts to enter the synchronized block on method A. Thread 1 is waiting for a notify, and thread 2 is waiting on the synchronized block. Everything is now waiting. Some other thread will have to notify the object on which thread 1 is waiting. This is just one scenario that can create a deadlock. There are all kinds of ways to do it.

like image 39
Steve11235 Avatar answered Sep 28 '22 08:09

Steve11235