Domanda

klocwork JD.LOCK.WAIT issue is reported when an Object.wait() method is called while the method is holding two or more locks.

klocwork says that waiting on a monitor while two locks are held may cause deadlock and the issue should be taken into account.

But I cannot understand why this causes deadlock.

Who can help me understand this issue?

Following code is from klockwork. The JD.LOCK.WAIT issue occurs on line 14 lock.wait();.

String name;
synchronized void waitForCondition(Object lock) {
    try {
        synchronized(lock) {
            name = "aa";
            lock.wait();            //line 14
        }
    } catch (InterruptedException e) {
        return;
    }
}
È stato utile?

Soluzione

Lets say t1 enters the waitForCondition() method. So t1 now has this as a lock. Meanwhile, some other thread has just acquired lock object and is trying call waitForContion().

  • t2 holds lock but is waiting for this to enter waitForContion().

  • t1 holds this but is waiting for lock to exit waitForContion().

That is a deadlock. Neither of them can make any progress and are waiting on each other.

To avoid this, one strategy is to make sure any thread has all the resources it needs to complete. Here it means that lock and this can only be acquired together and not otherwise.

Also, when lock.wait() is called, only lock is released while this is not. So, in such a case no thread can call waitForContion() on that object.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top