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

Java gives us a range of options for running a task asynchronously, such as using Executors. Often we want to know when a task finishes, for example, to alert a user or start the next task. In this tutorial, we’ll look at different options for receiving notifications on the completion of a task depending on how we’re running our task in the first place.

2. Setup

First, let’s define a task we’d like to run and a callback interface through which we want to be alerted when the task completes.

For our task, we’ll implement Runnable. Runnable is an interface that we can use when we want something to run in a thread. We have to override the run() method and put our business logic inside. For our example, we’ll just print to the console so we know it’s run:

class Task implements Runnable{
    @Override
    public void run() {
        System.out.println("Task in progress");
        // Business logic goes here
    }
}

Then let’s create our Callback interface, we’ll have a single method that takes a String argument. This is a simple example but we could have anything needed here to make our alerts as useful as possible. Using an interface allows us to implement our solutions in a much more generic way. It means we can pass in different CallbackInterface implementations depending on our use case:

interface CallbackInterface {
    void taskDone(String details);
}

Let’s now implement that interface:

class Callback implements CallbackInterface {
    void taskDone(String details){
        System.out.println("task complete: " + details);
        // Alerts/notifications go here
    }
}

We’ll use these for each of our task-running options. This will make it clear we’re completing the same task and we’ll receive an alert from the same callback at the end every time.

3. Runnable Implementation

The first example we’ll look at is a simple implementation of the Runnable interface. We can provide our task and callback via the constructor, then in the overridden run() method call both:

class RunnableImpl implements Runnable {
    Runnable task;
    CallbackInterface callback;
    String taskDoneMessage;

    RunnableImpl(Runnable task, CallbackInterface callback, String taskDoneMessage) {
        this.task = task;
        this.callback = callback;
        this.taskDoneMessage = taskDoneMessage;
    }

    void run() {
        task.run();
        callback.taskDone(taskDoneMessage);
    }
}

Our setup here runs the task we provided and then invokes our callback method once the task finishes. We can see that in action:

@Test
void whenImplementingRunnable_thenReceiveNotificationOfCompletedTask() {
    Task task = new Task();
    Callback callback = new Callback();
    RunnableImpl runnableImpl = new RunnableImpl(task, callback, "ready for next task");
    runnableImpl.run();
}

If we check the logs for this test we see the two messages we’d expect:

Task in progress
task complete ready for next task

Of course, in a real application, we’d have business logic and real alerts occur.

4. Using CompletableFuture

Perhaps the simplest option to run a task asynchronously and be alerted upon completion is to use the CompletableFuture class. 

CompletableFuture was introduced in Java 8 and is an implementation of the Future interface. It allows us to perform multiple tasks in order, each running after the previous Future finishes. This is great for us here as we can run our task, and instruct the CompletableFuture to run our callback method after.

To put that plan into action we can first use CompletableFuture‘s runAsync() method. This method takes a Runnable and runs it for us, returning a CompletableFuture instance. We can then chain the thenAccept() method with our Callback.taskDone() method as the argument, which will be called once our task is complete:

@Test
void whenUsingCompletableFuture_thenReceiveNotificationOfCompletedTask() {
    Task task = new Task();
    Callback callback = new Callback();
    CompletableFuture.runAsync(task)
      .thenAccept(result -> callback.taskDone("completion details: " + result));
}

Running this produces output from the task followed by our Callback implementation as expected. Our task doesn’t return anything so result is null, but depending on our use case we could handle that differently.

5. Extending ThreadPoolExecutor

For some use cases, we may need to use a ThreadPoolExecutor, if we’re going to submit many tasks at once for example. ThreadPoolExecutor allows us to execute as many tasks as we need to, using the number of threads we specify when we instantiate it.

We can extend the ThreadPoolExecutor class and override the afterExecute() method so it will call our Callback implementation after each task:

class AlertingThreadPoolExecutor extends ThreadPoolExecutor {
    CallbackInterface callback;
    public AlertingThreadPoolExecutor(CallbackInterface callback) {
        super(1, 1, 60, TimeUnit.SECONDS, new ArrayBlockingQueue<>(10));
        this.callback = callback;
    }
    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
        callback.taskDone("runnable details here");
    }
}

In our constructor, we’ve called the super constructor with hardcoded values to give us a single thread to use. We’ve also set the keep-alive time for idle threads to 60 seconds and given ourselves a queue that will fit 10 tasks in it. We could fine-tune this to our specific application but this is all we need for a simple example. As expected when run this gives us the following output:

Task in progress
task complete runnable details here

6. Extending FutureTask

Our last alternative is to extend the FutureTask class. FutureTask is another implementation of the Future interface. It also implements Runnable, meaning we can submit instances of it to an ExecutorService. This class provides a method we can override called done() which will be called upon completion of the provided Runnable.

So with that in mind all we need to do here is extend FutureTask, override the done() method, and call our Callback implementation passed in via the constructor:

class AlertingFutureTask extends FutureTask<String> {
    CallbackInterface callback;
    public AlertingFutureTask(Runnable runnable, Callback callback) {
        super(runnable, null);
        this.callback = callback;
    }
    @Override
    protected void done() {
        callback.taskDone("alert alert");
    }
}

We can use this extension of FutureTask by creating an instance of it and an instance of ExecutorService. Then we submit our FutureTask to the ExecutorService:

@Test
void whenUsingFutureTask_thenReceiveNotificationOfCompletedTask(){
    Task task = new Task();
    Callback callback = new Callback();
    FutureTask<String> future = new AlertingFutureTask(task, callback);
    ExecutorService executor = Executors.newSingleThreadExecutor();
    executor.submit(future);
}

The output of that test is as expected – the task logs first and then our callback implementation logs:

Task in progress
task complete: task details here

7. Conclusion

In this article, we’ve looked at four ways of running the same task asynchronously, then receiving an alert indicating its completion. Three of the options involve extending or implementing an existing Java class or interface. These are the Runnable interface and the ThreadPoolExecutor and FutureTask classes. Each of these options gives us a high level of control and plenty of options to get the alerting behavior we want.

The final option is using CompletableFuture which is much more streamlined. We don’t need a separate class, we can perform everything in a line or two. For simple use cases or when we have everything wrapped up nicely in our Callback and Task classes this does the job well.

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)