eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

Partner – LambdaTest – NPI EA (cat= Testing)
announcement - icon

Distributed systems often come with complex challenges such as service-to-service communication, state management, asynchronous messaging, security, and more.

Dapr (Distributed Application Runtime) provides a set of APIs and building blocks to address these challenges, abstracting away infrastructure so we can focus on business logic.

In this tutorial, we'll focus on Dapr's pub/sub API for message brokering. Using its Spring Boot integration, we'll simplify the creation of a loosely coupled, portable, and easily testable pub/sub messaging system:

>> Flexible Pub/Sub Messaging With Spring Boot and Dapr

eBook – Java Concurrency – NPI (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

1. Overview

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.

Further reading:

Guide to the Synchronized Keyword in Java

This article discusses thread synchronization of methods, static methods, and instances in Java.

How to Start a Thread in Java

Explore different ways to start a thread and execute parallel tasks.

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. Not managing threads properly 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 the following:

We can better understand this from the following diagram depicting the life cycle of a Thread:

Java - Wait and Notify

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().

3. The wait() Method

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:

  • when we’ve executed synchronized instance method for the given object
  • when 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 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().

3.3. wait(long timeout, int nanos)

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.

4. notify() and notifyAll()

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.

4.1. notify()

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().

4.2. 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).

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 finishes sending it.
  • Similarly, the Sender shouldn’t attempt to send another packet unless the Receiver has already processed the previous packet.

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:

  • 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, the Receiver should wait for Sender to send the message.
    • If it’s false, Sender should wait for Receiver to receive the message.
  • The Sender uses the 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 the receive() method:
    • If the transfer was set to false by Sender, only then will it 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 received.

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

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.

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.

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:

  • 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);

            //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.

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. 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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

eBook – Java Concurrency – NPI (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook Jackson – NPI EA – 3 (cat = Jackson)