Java 未来异步?

Java Future asynchronous?

来自 Java 文档:

A Future represents the result of an asynchronous computation. Methods are provided to check if the computation is complete, to wait for its completion, and to retrieve the result of the computation.

如果有等待完成的方法,那还叫异步吗?我对异步操作的理解是,调用者调用它,然后转到其他任务。调用者会自动知道完成,结果。这有错吗?

My understanding of asynchronous operation is that caller can just make a call to it, and just move to some other task.

definition of asynchronous operation。该术语指的是时间,而不是协调技术。

其他线程在后台完成的任务随时发生。与原始线程协调是一个不相关的问题,“异步”术语既不要求也不否认。所以是的,当后台线程正在执行委托任务时,原始 thread/object 可以自由地继续做其他工作。发起人 thread/object 可能会或可能不会被告知任务完成。

And caller would come to know of the completion automatically, with result. Is this wrong?

是的,那是错误的。 委派的任务可能与原始 thread/object 无关。发起者 thread/object 可能对任务的完成没有兴趣,如果是这样的话,当然不希望以任何方式被打断。

即使发起线程确实关心委托任务的完成,根据定义异步并没有定义通知发起线程的工具。在 C-style 编码的过去,通常定义 call-back 函数。在 OOP there are various techniques by which the originating object may be notified. One of these techniques is for the originating object to check the task’s status by interrogating a Future

这在 Future class 文档中显示的示例代码中进行了演示:

interface ArchiveSearcher { String search(String target); }
class App {
  ExecutorService executor = ...
  ArchiveSearcher searcher = ...
  void showSearch(String target) throws InterruptedException {
    Callable<String> task = () -> searcher.search(target);
    Future<String> future = executor.submit(task);
    displayOtherThings(); // do other things while searching
    try {
      displayText(future.get()); // use future
    } catch (ExecutionException ex) { cleanup(); return; }
  }
}

请注意,Java 8 带来了新的和有用的 Future 实现。

有异步计算和异步交互。通常异步计算使用异步交互,同步计算使用同步交互。同步计算是线程,同步交互是阻塞队列、信号量等

但是同步和异步世界需要交互,这里Future出来了:它将异步操作的结果提供给同步计算(线程)。