I'm new to Java and is trying to learn the concept of guarded blocks. I saw the code and statement below from Java tutorial oracle. My questions are:
1) why "when a thread invokes d.wait, it must own the intrinsic lock for d"?
2) the statement also mentioned, "otherwise an error is throw". What kind of error is thrown?
public synchronized void guardedJoy() {
// This guard only loops once for each special event, which may not
// be the event we're waiting for.
while(!joy) {
try {
wait();
} catch (InterruptedException e) {}
}
System.out.println("Joy and efficiency have been achieved!");
}
Here is the article:
Why is this version of guardedJoy synchronized? Suppose d is the object we're using to invoke wait. When a thread invokes d.wait, it must own the intrinsic lock for d — otherwise an error is thrown. Invoking wait inside a synchronized method is a simple way to acquire the intrinsic lock.