I’m very confusing about these two descriptions:
- “The wait method blocks the calling thread and gives up the monitor lock”
- “The notify method unblocks one waiting thread but does not give up the monitor lock”
Here is my questions:
-
I know each object in Java has a lock, but what is the “monitor lock” means? is it the same as the oject’s lock?
-
Why notify method needs to give up the monitor lock?
-
If I try to make a object waiting with the following code:
class simpleTask extends Thread { int waitingTime; public simpleTask(int waitingTime) { this.waitingTime = waitingTime; } public void run() { synchronized(this) // this is a reference of current object { try { this.wait(waitingTime); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Like the first description above, is that means the the current object is blocked by synchronized keyword, and then wait method releases the lock?
Yes, they are the same thing. They are also occasionally called the object’s “mutex” and the object’s “primitive lock”. (But when someone talks about
Lock, they are talking about this Java interface … which is a different locking mechanism.)The
notifymethod doesn’t give up the lock. It is your code’s responsibility to give up the lock (i.e. leave the synchronized block or return from the synchronized method) after thenotifycall returns.Why is that necessary? Because any other thread that is currently waiting on that lock (in a
wait(...)call) has to reacquire that lock before thewaitcall can complete.Why did they design
notify/waitlike this? So that they can be used to implement condition variables.That is correct. When a thread calls
someObject.wait()its lock onsomeObjectis released … and then reacquired (by the same thread) before thewait()call returns. Of course, in the meantime the locksomeObjectmay have been acquired and released multiple times by other threads. The point is that whenwaitreturns, the thread that calledwaitwill have the lock.