实现说明
真正干活的是类 ResilientRace和函数 replica、main,其余都是接线。
非法状态在入口就被拒绝:抛出 IllegalStateException,而不是带着坏数据继续。
使用要点
- 文中所列导入语句严格限定于语言自带的标准模块范围。
- 每一步打印都带着自己的标签:
raw winner:、raw anyOf failed fast:、guarded winner:。 - 执行文件,
main会按顺序走完replica。
常见问题
遇到格式错误的数据会怎样?
守卫处(入口)会抛出 IllegalStateException,非法状态到不了主逻辑。
运行「CompletableFuture.anyOf 最快分支失败时的语义」会打印什么?
运行文件本身,raw winner:、raw anyOf failed fast:、guarded winner: 这些前缀各对应一段演示逻辑。
主签名形如 static CompletableFuture<String> replica(String name, long delayMs, boolean fail)
核心语句
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (fail) {
throw new IllegalStateException(name + " failed");
}
return name + "-ok";
});
CompletableFuture<Object> safe = CompletableFuture.anyOf(safeA, safeB);
CompletableFuture<String> safeB = replica("slow-healthy", 80, false);
代码示例
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class ResilientRace {
static CompletableFuture<String> replica(String name, long delayMs, boolean fail) {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
if (fail) {
throw new IllegalStateException(name + " failed");
}
return name + "-ok";
});
}
public static void main(String[] args) {
// Raw anyOf resolves with the fastest completion, even when it throws
CompletableFuture<Object> raw = CompletableFuture.anyOf(
replica("fast-broken", 15, true),
replica("slow-healthy", 80, false));
try {
System.out.println("raw winner: " + raw.join());
} catch (CompletionException ex) {
String msg = ex.getCause() != null ? ex.getCause().getMessage() : ex.getMessage();
System.out.println("raw anyOf failed fast: " + msg);
}
// Guard each branch so a failed fast mirror degrades cleanly
CompletableFuture<String> safeA = replica("fast-broken", 15, true)
.exceptionally(err -> "fallback-" + (err.getCause() != null ? err.getCause().getMessage() : err.getMessage()));
CompletableFuture<String> safeB = replica("slow-healthy", 80, false);
CompletableFuture<Object> safe = CompletableFuture.anyOf(safeA, safeB);
System.out.println("guarded winner: " + safe.join());
safeB.join();
}
}