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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

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

Browser testing is essential if you have a website or web applications that users interact with. Manual testing can be very helpful to an extent, but given the multiple browsers available, not to mention versions and operating system, testing everything manually becomes time-consuming and repetitive.

To help automate this process, Selenium is a popular choice for developers, as an open-source tool with a large and active community. What's more, we can further scale our automation testing by running on theLambdaTest cloud-based testing platform.

Read more through our step-by-step tutorial on how to set up Selenium tests with Java and run them on LambdaTest:

>> Automated Browser Testing With Selenium

Partner – Orkes – NPI EA (cat=Java)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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.

1. Introduction

In this article, we’re going to take a look at the LISTEN and NOTIFY commands within PostgreSQL. We’ll see what they are, how they can be used, and how we can utilize them from within our applications.

2. What Are LISTEN and NOTIFY?

PostgreSQL has support for asynchronous communication between the server and connected clients using the LISTEN and NOTIFY commands. These PostgreSQL-specific extensions enable us to use the database as a simple messaging system, allowing us to generate events out of the database that clients can react to. This can be useful for many purposes, such as real-time dashboards, cache invalidation, data auditing, and more.

2.1. Listening for Notifications

We use the LISTEN command to register interest in receiving events. This takes the name of the channel that we want to listen to:

postgres=# LISTEN my_channel;
LISTEN

Once we’ve done this, our connection can receive asynchronous notifications of events happening on this channel.

Every connection that registers interest in these notifications receives them, so the system effectively broadcasts the messages rather than delivering them to a single recipient. This means that we can use this mechanism to easily tell every single client about events that are happening within our database.

Note that if we’re using psql then we don’t receive notifications automatically. Instead, we need to execute our LISTEN command again, and we’ll get shown all of the notifications that have been raised since the last time:

postgres=# LISTEN my_channel;
LISTEN
.....
postgres=# LISTEN my_channel;
LISTEN
Asynchronous notification "my_channel" with payload "Hello, World!" received from server process with PID 66.

Here, we can see that some connection has raised an event with the payload “Hello, world!”, and our listening connection has been notified about it.

While there’s no maximum number of listeners we can register, each listener must keep its database connection open in order to receive notifications, so the maximum connection limit effectively acts as a limit. In addition, every listener will use some amount of resources, so having too many can potentially cause performance issues.

2.2. Raising Notifications

Now that we know how to listen for events, we also need to be able to raise them. We can raise events using the NOTIFY command. This takes both the channel name and the message to send:

postgres=# NOTIFY my_channel, 'Hello, World!';
NOTIFY

When this command is executed, all connections that have previously executed the appropriate LISTEN command can receive this event, as we saw earlier.

Our payload is optional, but if we either don’t provide one or provide NULL, then the system will act as if the empty string was provided. It also has a maximum size of 8,000 bytes. If we try to send more than that, we’ll get an error and no listeners will be notified.

Notifications take part in transactions. This means that if we raise a notification during an active transaction, the system won’t send it until the transaction commits. It also means that if the transaction rolls back, the system won’t send the notification at all.

2.3. Dynamic Messages

The NOTIFY command requires that the message sent is exactly specified. We’re not able to do anything to generate the message dynamically, including simple string concatenation:

postgres=# NOTIFY my_channel, 'Hello, ' || 'World';
ERROR:  syntax error at or near "||"
LINE 1: NOTIFY my_channel, 'Hello, ' || 'World!';

However, we can instead use the pg_notify function to generate our notifications. This can take any message formed in any way:

postgres=# SELECT pg_notify('my_channel', 'Hello, ' || 'World!');
 pg_notify
-----------

(1 row)

In this case, the channel name has to be provided as a string, and the payload as a separate string. We can construct these strings in any way we need, including by using the results of SQL statements.

2.4. Raising Events From Triggers

While we can raise events ourselves by executing the appropriate statements, we can also get the database to raise them for us automatically. For example, we can register trigger functions that execute at appropriate times, and these functions can also generate these notifications:

CREATE OR REPLACE FUNCTION notify_table_change() RETURNS TRIGGER AS $$
    BEGIN
        PERFORM pg_notify('table_change', TG_TABLE_NAME);
        RETURN NEW;
    END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER table_change 
    AFTER INSERT OR UPDATE OR DELETE ON table_name
    FOR EACH ROW EXECUTE PROCEDURE notify_table_change();

Once this is done, if anything happens to create, update, or delete rows in the table_name table, this trigger will automatically send a notification on the table_change channel with the name of the table that changed.

3. Raising Notifications With JDBC

We can raise notifications from JDBC exactly the same as we’ve already seen.

Firstly, we need to connect to the database. We can do this using the official drivers for now. Let’s add them to our build:

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>42.7.6</version>
</dependency>

We can then create a connection as normal:

Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "mysecretpassword");

Once we’re connected, we can raise notifications using either the NOTIFY command or the pg_notify() function:

try (Statement statement = connection.createStatement()) {
    statement.execute("NOTIFY my_channel, 'Hello, NOTIFY!'");
}

As we saw before, if we want to do anything more than just a bare string, such as using bind parameters, then we need to use pg_notify instead:

try (PreparedStatement statement = connection.prepareStatement("SELECT pg_notify(?, ?)")) {
    statement.setString(1, "my_channel");
    statement.setString(2, "Hello, pg_notify!");
    statement.execute();
}

Both approaches work the same way, and the system delivers the notifications exactly as expected:

postgres=# postgres=# LISTEN my_channel;
LISTEN
Asynchronous notification "my_channel" with payload "Hello, NOTIFY!" received from server process with PID 390.
Asynchronous notification "my_channel" with payload "Hello, pg_notify!" received from server process with PID 390.

Here, we can see that our listening session successfully received both notifications raised by the Java code.

4. Listening With the Official JDBC Drivers

While raising notifications with JDBC is straightforward, listening for them is more involved. Receiving asynchronous messages from the database isn’t an official part of the JDBC specification, so we need to resort to driver-specific functionality.

The first thing we need to do is execute our LISTEN statement:

try (Statement statement = connection.createStatement()) {
    statement.execute("LISTEN my_channel");
}

However, in order to receive the notifications themselves, we need to use the getNotifications() method on the raw PGConnection object. This means that we first need to ensure we’ve got the correct type of connection:

PGConnection pgConnection = connection.unwrap(org.postgresql.PGConnection.class);

We then call getNotifications() to get any notifications that have been received. We need to do this in a loop, polling the database at a suitable frequency:

while (!Thread.currentThread().isInterrupted()) {
    PGNotification[] notifications = pgConnection.getNotifications(1000);
    if (notifications != null) {
        // React to notifications
    }
}

When we receive notifications, we can react to them however we like. However, we won’t receive any more until the next time getNotifications() is called, so we need to remember not to stop this loop if we need to react efficiently to any more.

We have three different ways that getNotifications() can be called. The simplest is with no parameters, in which case it will return immediately with whatever notifications are outstanding. However, this is not the recommended solution. Instead, there is a version that takes a timeout, in milliseconds, that the thread will block:

PGNotification[] notifications = pgConnection.getNotifications(100);

In this case, the call will return after either this timeout passes or any notifications are available, whichever happens first.

If we call this version with a timeout value of 0, then this will block forever. This effectively means that we will only return as soon as any notifications are available. If we’re running this method on a dedicated thread, then this can help make things easier to manage since we’ll no longer need to do any idle waiting.

5. Listening with PGJDBC-NG

If we want to receive notifications without needing to poll the database, we can achieve this with some alternative drivers. The PGJDBC-NG drivers are compatible with PostgreSQL while offering some more advanced features, including the ability to register callbacks for notifications.

Before we can use them, we need to add them to our build:

<dependency>
    <groupId>com.impossibl.pgjdbc-ng</groupId>
    <artifactId>pgjdbc-ng</artifactId>
    <version>0.8.9</version>
</dependency>

We can then create a connection as normal, only this time we use a URL of type jdbc:pgsql instead of jdbc:postgresql. For example:

Connection connection = DriverManager.getConnection("jdbc:pgsql://localhost:5432/postgres", "postgres", "mysecretpassword");

We still need to execute our LISTEN command on the connection, exactly the same as before. However, this time, we’re able to register a listener to receive callbacks whenever a notification happens. In order to do this, we need to implement the PGNotificationListener interface:

class Listener implements PGNotificationListener {
    @Override
    public void notification(int processId, String channelName, String payload) {
        LOG.info("Received notification: Channel='{}', Payload='{}', PID={}",
                channelName, payload, processId);
    }
}

We can then register an instance of this with our connection:

PGConnection pgConnection = connection.unwrap(com.impossibl.postgres.api.jdbc.PGConnection.class);
pgConnection.addNotificationListener(new Listener());

At this point, as long as the connection is active, we’ll automatically receive notifications as soon as they get raised without needing to poll the database:

10:34:03.104 [PG-JDBC I/O (1)] INFO com.baeldung.listennotify.JdbcLiveTest -- Received notification: Channel='my_channel', Payload='Hello, NOTIFY!', PID=844
10:34:03.106 [PG-JDBC I/O (1)] INFO com.baeldung.listennotify.JdbcLiveTest -- Received notification: Channel='my_channel', Payload='Hello, pg_notify!', PID=844

Not only is this easier for us to manage, but it’s more efficient for our application since we’re no longer having to poll the database waiting for something to happen.

6. Conclusion

In this article, we’ve taken a brief look at the LISTEN and NOTIFY commands within PostgreSQL and how to make use of them from JDBC connections. The next time you need to be able to raise events from your database, why not give it a go.

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.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 Jackson – NPI EA – 3 (cat = Jackson)