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

时间:2014-09-02 22:09:04

标签: asynchronous guava

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

1 个答案:

答案 0 :(得分:4)

其中一个处理转换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();
        }
    }
}