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 hasthisas a lock. Meanwhile, some other thread has just acquiredlockobject and is trying callwaitForContion().t2 holds
lockbut is waiting forthisto enterwaitForContion().t1 holds
thisbut is waiting forlockto 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
lockandthiscan only be acquired together and not otherwise.Also, when
lock.wait()is called, onlylockis released whilethisis not. So, in such a case no thread can callwaitForContion()onthatobject.