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而已。

posted on 2017-01-05 15:33  反光的小鱼儿  阅读(316)  评论(0编辑  收藏  举报