Skip to content

Instantly share code, notes, and snippets.

@youssef3wi
Last active September 18, 2025 18:49
Show Gist options
  • Select an option

  • Save youssef3wi/d441061b78bd3cdac21b239ed85ab0d1 to your computer and use it in GitHub Desktop.

Select an option

Save youssef3wi/d441061b78bd3cdac21b239ed85ab0d1 to your computer and use it in GitHub Desktop.
An example that demystifies pg_notify using PostgreSQL's native connection.
import org.postgresql.PGNotification;
import org.postgresql.ds.PGSimpleDataSource;
import org.postgresql.jdbc.PgConnection;
import java.sql.SQLException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import static java.lang.Thread.ofVirtual;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
public class PgNotify {
private static final ScheduledExecutorService SCHEDULER = newSingleThreadScheduledExecutor(ofVirtual().factory());
private final ScheduledFuture<?> handler;
public PgNotify(PgConnection pgConnection) throws SQLException {
this.handler = SCHEDULER.scheduleAtFixedRate(() -> {
try {
// To receive notifications, you may need to run this SQL query
// SELECT pg_notify('<channel-name>', 'your-payload');
pgConnection.execSQLUpdate("LISTEN <channel-name>");
PGNotification[] notifications = pgConnection.getNotifications();
if (notifications.length > 0) {
System.out.printf("Notifications %d received: ", notifications.length);
for (PGNotification notification : notifications) {
System.out.print(notification.getParameter());
}
System.out.println();
}
} catch (SQLException e) {
getHandler().cancel(true);
}
}, 0, 10, TimeUnit.MILLISECONDS);
}
public ScheduledFuture<?> getHandler() {
return handler;
}
public static void main(String[] args) throws SQLException {
PGSimpleDataSource ds = new PGSimpleDataSource();
ds.setURL("jdbc:postgresql://localhost:5432/<your-database-name>");
PgConnection pgConnection = ds.getConnection().unwrap(PgConnection.class);
new PgNotify(pgConnection);
while (true) ;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment