Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

wait and notify() Methods in Java

$
0
0

1. Introduction

In this article, we’ll look at one of the most fundamental mechanisms in Java – thread synchronization.

We’ll first discuss some essential concurrency-related terms and methodologies.

And we’ll develop a simple application – where we’ll deal with concurrency issues, with the goal of better understanding wait() and notify().

2. Thread Synchronization in Java

In a multithreaded environment, multiple threads might try to modify the same resource. If threads aren’t managed properly, this will, of course, lead to consistency issues.

2.1. Guarded Blocks in Java

One tool we can use to coordinate actions of multiple threads in Java – is guarded blocks. Such blocks keep a check for a particular condition before resuming the execution.

With that in mind, we’ll make use of:

This can be better understood from the following diagram, that depicts the lifecycle of a Thread:

Please note that there are many ways of controlling this lifecycle; however, in this article, we’re going to focus only on wait() and notify().

3. The wait() Method

Simply put, when we call wait() – this forces the current thread to wait until some other thread invokes notify() or notifyAll() on the same object.

For this, the current thread must own the object’s monitor. According to Javadocs, this can happen when:

  • we’ve executed synchronized instance method for the given object
  • we’ve executed the body of a synchronized block on the given object
  • by executing synchronized static methods for objects of type Class

Note that only one active thread can own an object’s monitor at a time.

This wait() method comes with three overloaded signatures. Let’s have a look at these.

3.1. wait()

The wait() method causes the current thread to wait indefinitely until another thread either invokes notify() for this object or notifyAll().

3.2. wait(long timeout)

Using this method, we can specify a timeout after which thread will be woken up automatically. A thread can be woken up before reaching the timeout using notify() or notifyAll().

Note that calling wait(0) is the same as calling wait().

3.3. wait(long timeout, int nanos)

This is yet another signature providing the same functionality, with the only difference being that we can provide higher precision.

The total timeout period (in nanoseconds), is calculated as 1_000_000*timeout + nanos. 

4. notify() and notifyAll()

The notify() method is used for waking up threads that are waiting for an access to this object’s monitor.

There are two ways of notifying waiting threads.

4.1. notify()

For all threads waiting on this object’s monitor (by using any one of the wait() method), the method notify() notifies any one of them to wake up arbitrarily. The choice of exactly which thread to wake is non-deterministic and depends upon the implementation.

Since notify() wakes up a single random thread it can be used to implement mutually exclusive locking where threads are doing similar tasks, but in most cases, it would be more viable to implement notifyAll().

4.2. notifyAll()

This method simply wakes all threads that are waiting on this object’s monitor.

The awakened threads will complete in the usual manner – like any other thread.

But before we allow their execution to continue, always define a quick check for the condition required to proceed with the thread – because there may be some situations where the thread got woken up without receiving a notification (this scenario is discussed later in an example).

5. Sender-Receiver Synchronization Problem

Now that we understand the basics, let’s go through a simple SenderReceiver application – that will make use of the wait() and notify() methods to set up synchronization between them:

  • The Sender is supposed to send a data packet to the Receiver
  • The Receiver cannot process the data packet until the Sender is finished sending it
  • Similarly, the Sender mustn’t attempt to send another packet unless the Receiver has already processed the previous packet

Let’s first create Data class that consists of the data packet that will be sent from Sender to Receiver. We’ll use wait() and notifyAll() to set up synchronization between them:

public class Data {
    private String packet;
    
    // True if receiver should wait
    // False if sender should wait
    private boolean transfer = true;
 
    public synchronized void send(String packet) {
        while (!transfer) {
            try { 
                wait();
            } catch (InterruptedException e)  {
                Thread.currentThread().interrupt(); 
                Log.error("Thread interrupted", e); 
            }
        }
        transfer = false;
        
        this.packet = packet;
        notifyAll();
    }
 
    public synchronized String receive() {
        while (transfer) {
            try {
                wait();
            } catch (InterruptedException e)  {
                Thread.currentThread().interrupt(); 
                Log.error("Thread interrupted", e); 
            }
        }
        transfer = true;

        notifyAll();
        return packet;
    }
}

Let’s break down what’s going on here:

  • The packet variable denotes the data that is being transferred over the network
  • We have a boolean variable transfer – which the Sender and Receiver will use for synchronization:
    • If this variable is true, then the Receiver should wait for Sender to send the message
    • If it’s false, then Sender should wait for Receiver to receive the message
  • The Sender uses send() method to send data to the Receiver:
    • If transfer is false, we’ll wait by calling wait() on this thread
    • But when it is true, we toggle the status, set our message and call notifyAll() to wake up other threads to specify that a significant event has occurred and they can check if they can continue execution
  • Similarly, the Receiver will use receive() method:
    • If the transfer was set to false by Sender, then only it will proceed, otherwise we’ll call wait() on this thread
    • When the condition is met, we toggle the status, notify all waiting threads to wake up and return the data packet that was Receiver

5.1. Why Enclose wait() in a while Loop?

Since notify() and notifyAll() randomly wakes up threads that are waiting on this object’s monitor, it’s not always important that the condition is met. Sometimes it can happen that the thread is woken up, but the condition isn’t actually satisfied yet.

We can also define a check to save us from spurious wakeups – where a thread can wake up from waiting without ever having received a notification.

5.2. Why Do We Need to Synchronize send() and receive() Methods?

We placed these methods inside synchronized methods to provide intrinsic locks. If a thread calling wait() method does not own the inherent lock, an error will be thrown.

We’ll now create Sender and Receiver and implement the Runnable interface on both so that their instances can be executed by a thread.

Let’s first see how Sender will work:

public class Sender implements Runnable {
    private Data data;
 
    // standard constructors
 
    public void run() {
        String packets[] = {
          "First packet",
          "Second packet",
          "Third packet",
          "Fourth packet",
          "End"
        };
 
        for (String packet : packets) {
            data.send(packet);

            // Thread.sleep() to mimic heavy server-side processing
            try {
                Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
            } catch (InterruptedException e)  {
                Thread.currentThread().interrupt(); 
                Log.error("Thread interrupted", e); 
            }
        }
    }
}

For this Sender:

  • We’re creating some random data packets that will be sent across the network in packets[] array
  • For each packet, we’re merely calling send() 
  • Then we’re calling Thread.sleep() with random interval to mimic heavy server-side processing

Finally, let’s implement our Receiver:

public class Receiver implements Runnable {
    private Data load;
 
    // standard constructors
 
    public void run() {
        for(String receivedMessage = load.receive();
          !"End".equals(receivedMessage);
          receivedMessage = load.receive()) {
            
            System.out.println(receivedMessage);

            // ...
            try {
                Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); 
                Log.error("Thread interrupted", e); 
            }
        }
    }
}

Here, we’re simply calling load.receive() in the loop until we get the last “End” data packet.

Let’s now see this application in action:

public static void main(String[] args) {
    Data data = new Data();
    Thread sender = new Thread(new Sender(data));
    Thread receiver = new Thread(new Receiver(data));
    
    sender.start();
    receiver.start();
}

We’ll receive the following output:

First packet
Second packet
Third packet
Fourth packet

And here we are – we’ve received all data packets in the right, sequential order and successfully established the correct communication between our sender and receiver.

6. Conclusion

In this article, we discussed some core synchronization concepts in Java; more specifically, we focused on how we can use wait() and notify() to solve interesting synchronization problems. And finally, we went through a code sample where we applied these concepts in practice.

Before we wind down here, it’s worth mentioning that all these low-level APIs, such as wait(), notify() and notifyAll() – are traditional methods that work well, but higher-level mechanism are often simpler and better – such as Java’s native Lock and Condition interfaces (available in java.util.concurrent.locks package).

For more information on the java.util.concurrent package, visit our overview of the java.util.concurrent article, and Lock and Condition are covered in the guide to java.util.concurrent.Locks, here.

As always, the complete code snippets used in this article are available over on GitHub.


Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>