A queue of tasks must be processed sequentially. While the simplest approach involves blocking on each task's completion using .get() on the Future, this approach can lead to memory issues when managing numerous queues. The goal is to implement a non-blocking mechanism that notifies the caller when a task is complete, allowing tasks to be processed sequentially without blocking.
To avoid blocking, the solution involves defining a callback interface that receives parameters on task completion. This callback is then invoked at the end of each task.
class CallbackTask implements Runnable { private final Runnable task; private final Callback callback; CallbackTask(Runnable task, Callback callback) { this.task = task; this.callback = callback; } public void run() { task.run(); callback.complete(); } }
Java 8 introduced CompletableFuture, which provides a more comprehensive mechanism for creating asynchronous and conditional pipelines.
import java.util.concurrent.CompletableFuture; public class GetTaskNotificationWithoutBlocking { public static void main(String... argv) throws Exception { ExampleService svc = new ExampleService(); GetTaskNotificationWithoutBlocking listener = new GetTaskNotificationWithoutBlocking(); CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work); f.thenAccept(listener::notify); } }
In the ExampleService class:
class ExampleService { String work() { // Code to perform long-running task return "Result from long-running task"; } }
In the listener class:
class GetTaskNotificationWithoutBlocking { void notify(String msg) { // Code to handle the message from the completed task } }
The above is the detailed content of How to Get Task Completion Notifications Without Blocking in Java Executors?. For more information, please follow other related articles on the PHP Chinese website!