Home > Java > javaTutorial > body text

How to Get Task Completion Notifications Without Blocking in Java Executors?

Linda Hamilton
Release: 2024-11-17 05:57:03
Original
699 people have browsed it

How to Get Task Completion Notifications Without Blocking in Java Executors?

Java Executors: Notifying Without Blocking on Task Completion

Problem Statement

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.

Solution

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.

Custom Callback 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();
  }

}
Copy after login

CompletableFuture

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);
  }

}
Copy after login

In the ExampleService class:

class ExampleService {

  String work() {
    // Code to perform long-running task
    return "Result from long-running task";
  }

}
Copy after login

In the listener class:

class GetTaskNotificationWithoutBlocking {

  void notify(String msg) {
    // Code to handle the message from the completed task
  }

}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template