Home > Java > javaTutorial > body text

How Can Callbacks Enable Non-Blocking Task Completion Notifications in Java Executors?

DDD
Release: 2024-11-18 09:38:02
Original
812 people have browsed it

How Can Callbacks Enable Non-Blocking Task Completion Notifications in Java Executors?

Java Executors: Non-Blocking Notifications for Task Completion

When faced with processing numerous tasks through an executor service, blocking can become a significant obstacle due to stack space constraints. To circumvent this issue, consider employing a callback approach, where tasks submit non-blocking notifications upon completion.

Creating a Callback Interface

Define a callback interface encapsulating the desired parameters for completion notification. In the provided code example:

public interface Callback {
  void complete();
}
Copy after login

Wrapping Tasks with a Callback

Utilize this callback interface to create a wrapper class for Runnable tasks:

class CallbackTask implements Runnable {
  private final Runnable task;
  private final Callback callback;

  CallbackTask(Runnable task, Callback callback) {
    this.task = task;
    this.callback = callback;
  }

  @Override
  public void run() {
    task.run();
    callback.complete();
  }
}
Copy after login

Submitting Tasks with Callbacks

With the callback wrapper in place, submit tasks to the executor service as follows:

ExecutorService executor = Executors.newSingleThreadExecutor();
executor.submit(new CallbackTask(task, callback));
Copy after login

Notification Callback

Implement the callback to handle completion notifications and execute the next task from the queue:

public class CallbackImpl implements Callback {
  private Queue<Task> queue;

  @Override
  public void complete() {
    if (!queue.isEmpty()) {
      executor.submit(new CallbackTask(queue.poll(), this));
    }
  }
}
Copy after login

Java 8's CompletableFuture

Since Java 8, the CompletableFuture class offers a more comprehensive approach for creating and managing asynchronous processes:

CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work);
f.thenAccept(listener::notify);
Copy after login

This code creates a CompletableFuture representing the asynchronous task, and defines a callback to be triggered upon its completion.

The above is the detailed content of How Can Callbacks Enable Non-Blocking Task Completion Notifications 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template