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.
As always, the full code for the examples is available over on GitHub.