Java Reference
In-Depth Information
How is a thread placed in the wait set? Note that a thread can be placed in the wait set of an object monitor only
if it once acquired the object's monitor lock. Once a thread has acquired the object's monitor lock, it must call the
wait()
method of the object in order to place itself into the wait set. This means a thread must always call the
wait()
method from inside a
synchronized
method or a block. The
wait()
method is defined in the
java.lang.Object
class
and it is declared
final
; that is, no other class in Java can override this method. You must consider the following two
rules before you call the
wait()
method of an object.
Rule #1
The call to the
wait()
method must be placed inside a
synchronized
method (static or non-static) or a
synchronized
block.
Rule #2
The
wait()
method must be called on the object whose monitor the current thread has acquired. It throws a
java.lang.InterruptedException
. The code that calls this method must handle this exception. The
wait()
method
throws an
IllegalMonitorStateException
when the current thread is not the owner of the object's monitor. The
following snippet of code does not place the
wait()
method call inside a
try-catch
to keep the code simple and readable.
For example, inside a
synchronized
non-static method, the call to the
wait()
method may look like the following:
public class WaitMethodCall {
// Object that is used to synchronize a block
private Object objectRef = new Object();
public synchronized void someMethod_1() {
// The thread running here has already acquired the monitor lock on
// the object represented by the reference this because it is a
// synchronized and non-static method
// other statements go here
while (some condition is true) {
// It is ok to call the wait() method on this, because the
// current thread possesses monitor lock on this
this.wait();
}
// other statements go here
}
public static synchronized void someMethod_2() {
// The thread executing here has already acquired the monitor lock on
// the class object represented by the WaitMethodCall.class reference
// because it is a synchronized and static method
while (some condition is true) {
// It is ok to call the wait() method on WaitMethodCall.class
// because the current thread possesses monitor lock on
// WaitMethodCall.class object
WaitMethodCall.class.wait();
}
// other statements go here
}