asynchronous - Google Guava 中的 Function 和 AsyncFunction 有什么区别?

标签 asynchronous guava

在内部,Function 和 Async Function 都是非阻塞的(对吗?)。那么,为什么我们有 AsyncFunction。区别只是一个返回 ListenableFuture 对象,另一个返回对象吗?

最佳答案

例如,其中一个涉及转换 Iterable,另一个则涉及从一个 ListenableFuture 转换(可能是异步)到另一个。这些概念完全不同,处理不同的事情。

这是 AsyncFunction 的一个小示例,基本上我们异步获取一个 String,然后将该 String 异步转换为另一个 String。但这只是一个示例..

public class GuavaAsyncFunction {
    public static void main(String[] args) {

        ExecutorService deletegate = Executors.newFixedThreadPool(1);
        ExecutorService deletegateForAsyncFunction = Executors.newFixedThreadPool(1);

        ListeningExecutorService pool = MoreExecutors.listeningDecorator(deletegate);
        ListeningExecutorService poolForAsyncFunction = MoreExecutors.listeningDecorator(deletegateForAsyncFunction);
        ListenableFuture<String> resultFromWorker = pool.submit(new Worker());

        ListenableFuture<String> finalResult = Futures.transform(resultFromWorker, new AsyncTransformation(poolForAsyncFunction));

        Futures.addCallback(finalResult, new MyFutureCallback());

    }

    private static final class Worker implements Callable<String> {
        public String call() throws Exception {
            try {
                System.out.println("Executing in thread="+Thread.currentThread().getName());
                //simultate some work
                TimeUnit.SECONDS.sleep(3);
            } catch(InterruptedException ex){
                ex.printStackTrace();
            }
            return "CALCULATED_VALUE";
        }
    }

    /**
     * Almost like Function transformation but it is asynchronous
     */
    private static final class AsyncTransformation implements AsyncFunction<String, String> {

        private final ListeningExecutorService poolToRunFunctionIn;

        public AsyncTransformation(ListeningExecutorService poolToRunFunctionIn){
            this.poolToRunFunctionIn = poolToRunFunctionIn;
        }

        public ListenableFuture<String> apply(String input) throws Exception {
            return poolToRunFunctionIn.submit(new FunctionWorker(input));
        }

        /**
         * 'worker' for the AsyncFunction
         */
        private static final class FunctionWorker implements Callable<String> {
            private final String input;
            public FunctionWorker(String input){
                this.input = input;
            }
            public String call() throws Exception {
                try {
                    System.out.println("Executing in thread="+Thread.currentThread().getName());
                    TimeUnit.SECONDS.sleep(3);
                } catch(InterruptedException ex){
                    ex.printStackTrace();
                }
                return input + "_TRANSFORMED";
            }
        }
    }

    /**
     * what do to when the ListenableFuture has been processed
     */
    private static final class MyFutureCallback implements FutureCallback<String> {
        public void onSuccess(String result) {
            System.out.println("Result from computation = " + result);
        }

        public void onFailure(Throwable t) {
            t.printStackTrace();
        }
    }
}

关于asynchronous - Google Guava 中的 Function 和 AsyncFunction 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25633159/

相关文章:

java - Guava 中有什么类似于 Functional Java 的 Effect 吗?

android - ListView 图像仅在可见时显示

Java 使用 spring 异步保存/更新数据到数据库中

ios - 如何在 Ios Extension 中使用第三方库?

javascript - Node.js 循环中的 setTimeout

node.js - 使用 NodeJS 异步调用多个 API,无论每个 API 的结果如何

java - Guava 的 Streams::findLast 实现

java - 确保所有集合元素都为非空的现有实用程序方法

java - 为什么 ImmutableMap.builder().build() 没有选择正确的类型参数?

java - 谷歌集合中的集合 map