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

相关文章:

  • 2021-11-01
  • 2021-10-26
  • 2021-07-16
  • 2021-12-14
  • 2021-12-02
  • 2021-07-28
  • 2022-02-09
  • 2021-07-31
猜你喜欢
  • 2022-03-07
  • 2022-02-03
  • 2021-06-22
  • 2021-11-08
  • 2022-02-20
  • 2021-07-13
  • 2021-06-23
相关资源
相似解决方案