Witscale Test Center

12.4 Thread interaction with wait(), notify() and notifyAll() > 12.4.2 The wait(), notify() and notifyAll() methods


12.4.2 The wait(), notify() and notifyAll() methods

Java threads can use the methods wait(), notify() and notifyAll() (including their overloaded versions) to implement the wait-and-notify mechanism. Before we see the actual implementation, you must remember following key points about using these methods -

 

A thread that invokes the wait() and notify() methods on an object, must own that object’s lock.

Since the synchronized code (on some object) makes sure that the thread executing it has that object’s lock, the thread should always call that object’s wait(), notify and notifyAll() methods in a synchronized code.

 

@

You code compiles even if you do not enclose the call object, say myObj.wait() or notify() in synchronized code (synchronized on myObj as ( synchronized(myObj) {} ). But you will get a runtime exception if the thread does not own myObj’s lock at runtime.

 

The methods wait(),notify() and notifyAll() are instance methods of Object.

Every Java object has a pool of threads that are waiting for a notification from the object. A thread gets on to an object’s waiting pool by executing the wait() method on that object. From that moment, the thread cease to execute until the notify() method of the same object is called. For example, the analyzer thread in the stock application should call stock.wait() method to start waiting (till the stock changes). The modifier thread should call stock.notify() method after it modifies the stock to notify the waiting analyzer thread.

 

Java maintains two types of thread pools for any object. One thread pool consists of threads waiting(seeking) to get the  lock on the object. A java thread enters this pool when it encounters a synchronized code (on that object) while executing. Another thread pool is of threads waiting for notification. A java thread enters this pool when it invokes the wait() method (on that object) while executing. Be careful when a question asks you when a waiting thread will come out of waiting state because the answer depends on what exactly (lock or notification?) the thread is waiting?