Java Google Guava Concurrency 中 Futures.addCallBack() 和 Futures.transform() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23735683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:56:44  来源:igfitidea点击:

Difference between Futures.addCallBack() and Futures.transform() in Google Guava Concurrency

javaasynchronousconcurrencyguava

提问by Chandra Sekhar

What is the difference between Futures.addCallBack()and Futures.transform()in Google Guava Concurrency.

是什么区别Futures.addCallBack(),并Futures.transform()谷歌番石榴并发

As per the documentation:

根据文档:

Futures.addCallBack():
addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback)Registers separate success and failure callbacks to be run when the Future's computation is complete or, if the computation is already complete, immediately.

Futures.addCallBack()
addCallback(ListenableFuture<V> future, FutureCallback<? super V> callback)注册单独的成功和失败回调,以在 Future 的计算完成时运行,或者,如果计算已经完成,则立即运行。

Futures.transform():
transform(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function)Returns a new ListenableFuture whose result is asynchronously derived from the result of the given Future.

Futures.transform():
transform(ListenableFuture<I> input, AsyncFunction<? super I,? extends O> function)返回一个新的 ListenableFuture,其结果异步派生自给定 Future 的结果。

As per my understanding addCallback()will register success or failure callback when asynchronous processing is completed. In this case we can handle the out put based on success or failure conditions (example: logging, flow control..etc). and transform()only return the Asynchronous object back. So difference is only Callback?.

根据我的理解addCallback(),异步处理完成后会注册成功或失败回调。在这种情况下,我们可以根据成功或失败条件(例如:日志记录、流控制等)处理输出。并且transform()只返回异步对象。所以区别只是回调?。

  1. whether my understanding is correct?
  2. Which is the best one to use with asynchronous processing?
  3. If I need to call multiple asynchronous methods in a sequence, is there any best practice for that?
  4. What is the difference between using AsyncFunctionand Functionin transform(ListenableFuture<I> input, Function/AsyncFunction <? super I,? extends O> function)? (AsyncFunction only used for nested Futures.transform()?)
  1. 我的理解是否正确?
  2. 哪个最好用于异步处理?
  3. 如果我需要按顺序调用多个异步方法,是否有最佳实践?
  4. usingAsyncFunctionFunctionin和有transform(ListenableFuture<I> input, Function/AsyncFunction <? super I,? extends O> function)什么不一样?(AsyncFunction 仅用于嵌套Futures.transform()?)

What I tried:
I try to write code like below, whether this is a good practice or not.

我的尝试:
我尝试编写如下代码,无论这是否是一个好习惯。

public ListenableFuture<MyObject> doSomething() {
    logger.info( "Entered in dosomething() Method." );  

    ListeningExecutorService executor =
            MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(50));

    ListenableFuture<MyObject> myAsyncObject =
            calculator.calculateSomething(input);
    //internally calculator.calculateSomething() have multiple asynchronous
    // calls and I am using Futures.transform(), without callback.

    Futures.addCallback(myAsyncObject, new FutureCallback<MyObject>() {
        public void onSuccess(MyObject result) {
            logger.info( "Calculation Completed successfully." );
            //TODO: check for success and log it.
        }

        public void onFailure(Throwable thrown) {
            logErrorDetails(thrown);
        }
    }, executor);

    executor.shutdown();

    return myAsyncObject;
}

回答by rds

Well you didn't write the full method signature in your question

那么你没有在你的问题中写下完整的方法签名

  • addCallbackreturns nothing
  • transformreturns a future that holds result of the function (if the input succeeded) or the original input's failure (if not). This allows to chain transformations, with a fluent syntax.
  • addCallback什么都不返回
  • transform返回保存函数结果(如果输入成功)或原始输入失败(如果不成功)的未来。这允许使用流畅的语法链接转换。

I've not used AsyncFunction, but I understand they add one level of asynchronicity, ie the result of the Futureis another Future.

我没有使用过AsyncFunction,但我知道他们增加了一个异步级别,即 的结果Future是另一个Future