Understanding java.lang.Object.wait()



Hi,

I am a bit confused as how wait() actually works. I know the purpose
of this method but what I wanted to know is when a few threads waiting
on a certain object lock and they are signaled via notifyAll(), how
does one of the threads on the waiting list for that object lock gets
the lock and what would happen to the other threads? Let me elaborate
my confusion in the following simple example:

Thread1, Thread2, Thread3 they all waiting on "obj" that is being
processed by Thread4. Thread4 runs as following:

public void run() {

synchronized (obj) {
try {
// do some processing on obj status
obj.notifyAll()
} catch (InterruptedException ie) { }
}
}



Now, I understand that notifyAll() ONLY notifies other threads
blocking on this object that the current thread is done with the
object is "ready" to release the lock. That is the actual release of
the lock occurs AFTER the code is out of synchronized block.

Having said that, what exactly happens when the waiting threads
receive such notification? That is:

// Other threads running block
public void run() {
synchronized (obj) {
while (some condition not being met) {
try {
obj.wait();
// (1)
} catch (InterruptedException ie) { }
// Some code to process
}
}

}



When "ALL THE THREADS" receive such signal, do they all "get out" of
wait() method and then whoever wins the contention would gets the lock
and the rest are put on the waiting list once they "failed" the
condition? Or ONLY a thread that gets the lock is allowed to finish
its wait() and continue on with execution? What I want to know is does
JVM even allow the threads to get out of wait() before actually
acquiring the lock?

Unfortunately the wait() method is implemented in a native code so I
can't figure out the inner work of this method from the source code.


Thank You

.



Relevant Pages

  • Re: Understanding java.lang.Object.wait()
    ... of this method but what I wanted to know is when a few threads waiting ... does one of the threads on the waiting list for that object lock gets ... my confusion in the following simple example: ... // do some processing on obj status ...
    (comp.lang.java.programmer)
  • Re: Question on Threads
    ... Threads seize their current execution in two ways ... They would be put in a Object Lock Monitor Queue. ...
    (comp.lang.java.programmer)
  • Re: Object locking and deletion/creation
    ... Acquire the list lock. ... Acquire the object lock. ... Dmitriy V'jukov ...
    (comp.programming.threads)
  • Re: Synchronizing on Local Lock Object? Buggy?
    ... seems to me that the LOCK is local thus if a thread tried to lock on ... each thread executing the code has a different object. ... final Object LOCK = SomeClass.getMyLockObject; ... Maybe tempMap is null, by the time ...
    (comp.lang.java.programmer)
  • Re: a[3} slower than a.x; a.z; a.z
    ... String^ ReadFirstLineFromFile{ ... lock l(obj); ... … do something with shared state...
    (comp.lang.cpp)