FutureFallback接口用作Future失败时的备份或默认值。
public class FutureFallbackImpl implements FutureFallback<String> {
@Override
public ListenableFuture<String> create(Throwable t) throws Exception {
if (t instanceof FileNotFoundException) {
SettableFuture<String> settableFuture =
SettableFuture.create();
settableFuture.set("Not Found");
return settableFuture;
}
throw new Exception(t);
}
}
这个例子中,假设我们尝试异步的获取文件,但是文件不存在我们也不关心
这样,可以创建一个Futrue对象并设置Not Found。否则继续抛出异常