我有这样的手术
public void createFuture() {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5);
future.thenApply(i -> {
if (i == 5) {
System.out.println("hello,i equals to 5 so expensive operations are unnecessary");
}
return i;
}).thenApply(i -> {
if (i != 5) {
System.out.println("Expensive operation");
}
return i;
}).thenApply(i -> {
if (i != 5) {
System.out.println("Expensive operation");
}
return i;
}).thenApply(i -> {
if (i != 5) {
System.out.println("Expensive operation");
}
return i;
}).thenApply(i -> {
if (i != 5) {
System.out.println("Expensive operation");
}
return i;
});
}
在第一块中,我检查了一些条件(i == 5)
,如果为真,则不需要其余操作。我不想抛出异常来取消其余部分,因为这不是例外情况。除了将布尔值传递给每个操作之外,还有其他好方法吗?