guava学习--FutureFallback

FutureFallback提供一个Future的备用来替代之前失败的Future,常被用来作为Future的备份或者默认的值。

@Test
public void testFuturesFallback() throws ExecutionException, InterruptedException {
listenableFuture = executorService.submit(new Callable<String>() {
@Override
public String call() throws Exception {
throw new RuntimeException();
}
});
FutureFallback<String> futureFallback = new FutureFallback<String>() {
@Override
public ListenableFuture create(Throwable t) throws Exception {
if (t instanceof RuntimeException) {
SettableFuture<String> settableFuture =
SettableFuture.create();
settableFuture.set("Not Found");
return settableFuture;
}
throw new Exception(t);
}
};
ListenableFuture<String> lf =
Futures.withFallback(listenableFuture,futureFallback);
assertThat(lf.get(), is("Not Found"));
}

代码的逻辑其实和AsyncFunction 一样,只是这里是Futures.withFallback而已。

上一篇:Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Inverse'.


下一篇:javascript封装与多态的体现