在内部,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/