0
在内部,函数和异步函数都是非阻塞的(对吧?)。那么,为什么我们有AsyncFunction。只有一个返回ListenableFuture对象和另一个返回对象的区别?Google Guava中的Function和AsyncFunction有什么区别?
在内部,函数和异步函数都是非阻塞的(对吧?)。那么,为什么我们有AsyncFunction。只有一个返回ListenableFuture对象和另一个返回对象的区别?Google Guava中的Function和AsyncFunction有什么区别?
那么他们之一处理转换Iterable例如和一个转换(可能异步)从一个ListenableFuture到另一个。这些概念是完全不同的,并处理不同的事情。
这里是一个AsyncFunction的小例子,基本上我们异步获取一个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();
}
}
}
我怀疑这是如何工作。谢谢你确认我的怀疑。 – wlan0 2014-09-03 20:37:00