简体   繁体   English

Listenablefuture与Completablefuture

[英]Listenablefuture vs Completablefuture

I tried hard but didn't find any article or blog which clearly compares ListenableFuture and CompletableFuture , and provides a good analysis. 我努力了,但没有发现任何明显比较ListenableFutureCompletableFuture文章或博客,并提供了一个很好的分析。

So if anyone can explain or point me to such a blog or article, it will be really good for me. 因此,如果有人能够解释或指向我这样的博客或文章,那对我来说真的很好。

Both ListenableFuture and CompletableFuture have an advantage over its parent class Future by allowing the caller to "register" in one way or another a callback to be called when the async action has been completed. ListenableFutureCompletableFuture都优于其父类Future ,允许调用者以某种方式“注册”在异步操作完成时调用的回调。

With Future you can do this: 有了Future,你可以这样做:

ExecutorService executor = ...;
Future f = executor.submit(...);
f.get();

f.get() gets blocked until the async action is completed. f.get()被阻塞,直到异步操作完成。

With ListenableFuture you can register a callback like this: 使用ListenableFuture,您可以注册这样的回调:

ListenableFuture listenable = service.submit(...);
    Futures.addCallback(listenable, new FutureCallback<Object>() {
                @Override
                public void onSuccess(Object o) {
                    //handle on success
                }

                @Override
                public void onFailure(Throwable throwable) {
                   //handle on failure
                }
            })

With CompletableFuture you can also register a callback for when the task is complete, but it is different from ListenableFuture in that it can be completed from any thread that wants it to complete. 使用CompletableFuture,您还可以在任务完成时注册回调,但它与ListenableFuture的不同之处在于它可以从任何希望它完成的线程中完成。

CompletableFuture completableFuture = new CompletableFuture();
    completableFuture.whenComplete(new BiConsumer() {
        @Override
        public void accept(Object o, Object o2) {
            //handle complete
        }
    }); // complete the task
    completableFuture.complete(new Object())

When a thread calls complete on the task, the value received from a call to get() is set with the parameter value if the task is not already completed. 当线程调用任务完成时,如果任务尚未完成,则使用参数值设置从get()调用接收的值。

Read about CompletableFuture 阅读CompletableFuture

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM