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;
}
}
Lets say t1 enters the
waitForCondition()
method. So t1 now hasthis
as a lock. Meanwhile, some other thread has just acquiredlock
object and is trying callwaitForContion()
.t2 holds
lock
but is waiting forthis
to enterwaitForContion()
.t1 holds
this
but is waiting forlock
to exitwaitForContion()
.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
andthis
can only be acquired together and not otherwise.Also, when
lock.wait()
is called, onlylock
is released whilethis
is not. So, in such a case no thread can callwaitForContion()
onthat
object.