问题

假设我有一个完整的任务队列,我需要提交给执行者服务。我希望他们一次处理一个。我能想到的最简单的方法是:

  • 从队列中获取任务
  • 将其提交给遗嘱执行人
  • 在返回的Future上调用.get并阻塞,直到结果可用
  • 从队列中取出另一项任务......

但是,我试图完全避免阻塞。如果我有10,000个这样的队列,需要一次处理一个任务,我将耗尽堆栈空间,因为它们中的大多数将保持被阻塞的线程。

我想要的是提交一个任务并提供一个在任务完成时调用的回调。我将使用该回叫通知作为发送下一个任务的标志。 (functionaljava和jetlang显然使用了这种非阻塞算法,但我无法理解他们的代码)

我怎么能使用JDK的java.util.concurrent来做这件事,而不是编写我自己的执行器服务?

(向我提供这些任务的队列本身可能会阻塞,但这是一个需要解决的问题)


#1 热门回答(119 赞)

定义回调接口以接收要在完成通知中传递的任何参数。然后在任务结束时调用它。

你甚至可以为Runnable任务编写一般包装器,并将它们提交到ExecutorService。或者,请参阅下面的Java 8内置机制。

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

}

借助CompletableFuture,Java 8包含了一种更复杂的方法来组成流程,其中流程可以异步和有条件地完成。这是一个人为但完整的通知示例。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

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);
    System.out.println("Exiting main()");
  }

  void notify(String msg) {
    System.out.println("Received message: " + msg);
  }

}

class ExampleService {

  String work() {
    sleep(7000, TimeUnit.MILLISECONDS); /* Pretend to be busy... */
    char[] str = new char[5];
    ThreadLocalRandom current = ThreadLocalRandom.current();
    for (int idx = 0; idx < str.length; ++idx)
      str[idx] = (char) ('A' + current.nextInt(26));
    String msg = new String(str);
    System.out.println("Generated message: " + msg);
    return msg;
  }

  public static void sleep(long average, TimeUnit unit) {
    String name = Thread.currentThread().getName();
    long timeout = Math.min(exponential(average), Math.multiplyExact(10, average));
    System.out.printf("%s sleeping %d %s...%n", name, timeout, unit);
    try {
      unit.sleep(timeout);
      System.out.println(name + " awoke.");
    } catch (InterruptedException abort) {
      Thread.currentThread().interrupt();
      System.out.println(name + " interrupted.");
    }
  }

  public static long exponential(long avg) {
    return (long) (avg * -Math.log(1 - ThreadLocalRandom.current().nextDouble()));
  }

}

#2 热门回答(46 赞)

使用Guava's listenable future API并添加回调。参看来自网站:

ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
ListenableFuture<Explosion> explosion = service.submit(new Callable<Explosion>() {
  public Explosion call() {
    return pushBigRedButton();
  }
});
Futures.addCallback(explosion, new FutureCallback<Explosion>() {
  // we want this handler to run immediately after we push the big red button!
  public void onSuccess(Explosion explosion) {
    walkAwayFrom(explosion);
  }
  public void onFailure(Throwable thrown) {
    battleArchNemesis(); // escaped the explosion!
  }
});

#3 热门回答(44 赞)

在Java 8中,你可以使用CompletableFuture。这是我在我的代码中的一个例子,我用它从我的用户服务中获取用户,将它们映射到我的视图对象,然后更新我的视图或显示错误对话框(这是一个GUI应用程序):

CompletableFuture.supplyAsync(
            userService::listUsers
    ).thenApply(
            this::mapUsersToUserViews
    ).thenAccept(
            this::updateView
    ).exceptionally(
            throwable -> { showErrorDialogFor(throwable); return null; }
    );

它以异步方式执行。我使用两种私有方法:8374​​60936和updateView


原文链接