从回调中设置未来

Set future from callback

我想实现以下伪代码说明的内容:

int functionA() {
    Future res;
    // ...
    setCallbackForSomething(new Callback() {
        public void onCall() {
            // ...
            res = 5;
        }
    });
    // ...
    return doSomethingElse(res.get());
}

即functionA 阻塞直到调用回调,然后处理结果和 returns 东西。

Future 可以实现类似的功能吗?通常的用法,

Future res = executor.submit(...);
...
res.get()

这里好像不行。我也无法改变我必须这样设置回调的事实。

Future 功能有限。来自 javadoc

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.

它只公开读取操作(cancel除外)。您将无法通过 Future 实现您想要的。

相反,由于 Java 8,您可以使用 CompletableFuture

A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.

你初始化CompletableFuture

CompletableFuture<Integer> res = new CompletableFuture<>();

并完成 normally or exceptionally

setCallbackForSomething(new Callback() {
    public void onCall() {
        // ...
        res.complete(5); // or handle exception
    }
});

而不是调用 get,您可以 chain a completion taskCompletableFuture 上调用 doSomethingElse

res.thenAccept(value -> doSomethingElse(value));

尽管您仍然可以根据需要调用 get,阻塞直到 future 完成。


在 Java8 之前,Guava 库提供了 SettableFuture to achieve the "set" part of a promised value. But it's also a ListenableFuture 因此您可以在完成时链接其他操作。