Search code examples
javamultithreadingwait

why "when a thread invokes d.wait, it must own the intrinsic lock for d"?


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.


Solution

  • 1) why "when a thread invokes d.wait, it must own the intrinsic lock for d"?

    Because the javadoc says it must!

    Why?

    Well the primary purpose of wait and notify are to implement condition variables and the like. In general, one thread waits for some other thread to notify it that some shared state has changed. If the waiting thread didn't have to wait within a lock, then there would be no guarantee that the state changes made by the second thread would be visible ... as per the Java memory model.

    You would also need to worry about races. For example, suppose a third thread that was also waiting on that same condition and got a different notification ... and only just got scheduled. Now you have two threads both checking the condition ... at the same type. (Note this only applies for some use-cases.)

    2) the statement also mentioned, "otherwise an error is throw". What kind of error is thrown?

    The javaoc says: "Throws ... IllegalMonitorStateException - if the current thread is not the owner of the object's monitor."


    Could you please tell me under what kind of potential circumstances that 'the current thread is not the owner of the object's monitor'?

    That would be when it hasn't acquired the lock by entering a synchronized block ... or equivalent.