
Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:
Once the early-adopter seats are all used, the price will go up and stay at $33/year.
Last updated: January 8, 2024
In this tutorial, 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().
In a multithreaded environment, multiple threads might try to modify the same resource. Not managing threads properly will of course lead to consistency issues.
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 the following:
We can better understand this from the following diagram depicting the life cycle of a Thread:
Please note that there are many ways of controlling this life cycle. However, in this article, we’re going to focus only on wait() and notify().
Simply put, calling wait() 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 in the following ways:
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.
The wait() method causes the current thread to wait indefinitely until another thread either invokes notify() for this object or notifyAll().
Using this method, we can specify a timeout after which a 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().
This is yet another signature providing the same functionality. The only difference here is that we can provide higher precision.
The total timeout period (in nanoseconds) is calculated as 1_000_000*timeout + nanos.
We use the notify() method for waking up threads that are waiting for access to this object’s monitor.
There are two ways of notifying waiting threads.
For all threads waiting on this object’s monitor (by using any one of the wait() methods), the method notify() notifies any one of them to wake up arbitrarily. The choice of exactly which thread to wake is nondeterministic and depends upon the implementation.
Since notify() wakes up a single random thread, we can use it to implement mutually exclusive locking where threads are doing similar tasks. But in most cases, it would be more viable to implement notifyAll().
This method simply wakes all threads that are waiting on this object’s monitor.
The awakened threads will compete in the usual manner, like any other thread that is trying to synchronize on this object.
But before we allow their execution to continue, always define a quick check for the condition required to proceed with the thread. This is because there may be some situations where the thread got woken up without receiving a notification (this scenario is discussed later in an example).
Now that we understand the basics, let’s go through a simple Sender–Receiver application that will make use of the wait() and notify() methods to set up synchronization between them:
Let’s first create a 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 String receive() {
while (transfer) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread Interrupted");
}
}
transfer = true;
String returnPacket = packet;
notifyAll();
return returnPacket;
}
public synchronized void send(String packet) {
while (!transfer) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread Interrupted");
}
}
transfer = false;
this.packet = packet;
notifyAll();
}
}
Let’s break down what’s going on here:
Since notify() and notifyAll() randomly wake up threads that are waiting on this object’s monitor, it’s not always important that the condition is met. Sometimes 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.
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.
First, we’ll 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();
System.err.println("Thread Interrupted");
}
}
}
}
Let’s take a closer look at this Sender:
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);
//Thread.sleep() to mimic heavy server-side processing
try {
Thread.sleep(ThreadLocalRandom.current().nextInt(1000, 5000));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Thread Interrupted");
}
}
}
}
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.
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. Finally, we went through a code sample where we applied these concepts in practice.
Before we close, 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 mechanisms 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.