【发布时间】:2019-02-26 07:26:04
【问题描述】:
有两个sn-ps代码。
在第一个中,我们从总是抛出一些异常的任务中创建 CompletableFuture。然后我们将“例外”方法应用于这个未来,然后是“接受”方法。我们不会将Accept 方法返回的新未来分配给任何变量。然后我们在原始未来调用“加入”。我们看到的是“异常”方法以及“thenAccept”已被调用。我们看到它是因为他们在输出中打印了适当的行。但是异常并没有被“异常”方法抑制。在这种情况下,抑制异常并为我们提供一些默认值正是我们对“异常”的期望。
在第二个 sn-p 中,我们做了几乎相同的操作,但将新返回的未来分配给变量并在其上调用“join”。在这种情况下,正如预期的那样,异常被抑制了。
从我的第一部分的观点来看,一致的行为要么不抑制异常,也不调用“异常”和“thenAccept”,或者异常调用并抑制异常。
为什么我们之间有一些东西?
第一个sn-p:
public class TestClass {
public static void main(String[] args) {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(TestClass::doSomethingForInteger);
future.exceptionally(e -> {
System.out.println("Exceptionally");
return 42;
})
.thenAccept(r -> {
System.out.println("Accept");
});
future.join();
}
private static int doSomethingForInteger() {
throw new IllegalArgumentException("Error");
}
}
第二个sn-p:
public class TestClass {
public static void main(String[] args) {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(TestClass::doSomethingForInteger);
CompletableFuture<Void> voidCompletableFuture = future.exceptionally(e -> {
System.out.println("Exceptionally");
return 42;
})
.thenAccept(r -> {
System.out.println("Accept");
});
voidCompletableFuture.join();
}
private static int doSomethingForInteger() {
throw new IllegalArgumentException("Error");
}
}
【问题讨论】:
标签: java java.util.concurrent completable-future forkjoinpool