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

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

DDD
DDDOriginal
2024-11-18 09:38:02894browse

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

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

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

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

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

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!

Statement:
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