|
While working on shared objects, sometimes a thread might want to take action only when an object is modified by some other thread. In such case, the thread must wait till some other thread finishes its job. But how the waiting thread will know that the modifier thread has modified the object? For that, the waiting thread must be able to communicate with the modifier thread. Java threads communicate about the status of shared objects using the wait-and-notify mechanism. Let us try to understand this mechanism of thread interaction with one shared object and two threads operating on it. Imagine that we have a stock object and two threads. One thread modifies the stock’s price. Let us call it the modifier thread. Another thread analyses the price of stock object and suggests whether the stock is good for buying. Let us call it the analyzer thread. The analyzer thread needs to perform analysis whenever the stock price is modified. With the threading techniques we learned so far, you can solve this problem as:
1. Create the stock object.
2. Create a modifier thread that first acquires the stock object’s lock and then modifies its price.
3. Create the analyzer thread. This thread will iteratively check the stock price to see if the stock price has been modified. If it is indeed modified, this thread performs analysis and suggests either buying or selling the stock.
In this application, the stock analyzer thread needs to keep checking the status of stock because it has no other way of knowing about the price change. Since the stock price is modified only by modifier thread, the analyzer may say, “I don’t want to keep checking for stock price change every two minutes. I am just going to wait here (take some rest). Could modifier be kind enough to notify me when the it modifies the stock’s price so that I can be back to do some analysis”. In other words, the thread is requesting to be notified about the changes instead of continuously polling for changes in stock. Figure 12.13 a high-level working of wait-notify mechanism in the stock application.

Figure 12.13 Wait-and-notify mechanism in stock application
The analyzer thread can relax and do nothing while waiting. The modifier thread modifies the stock price and sends notification to analyzer. After getting the notification, the analyzer will come out of the waiting room and do its job. This is the how the wait-and-notify mechanism works with Java threads. Fundamentally, it is same even for other applications. We took the example of stocks, but this concept is universal. You can apply it to any object and threads operating on it. Some threads modify the object (modifier or producer threads) while some use the object (consumer threads). Often consumer threads wait for the notification from the modifiers. Let us see how to implement wait-and-notify using the three methods java.lang.Object provides.