[英]Why Java 8 CompletableFuture thenCompose generates different exception depending on the order of completion?
[英]Completion order of CompletableFuture
當 CompletableFuture 有多個依賴項時,我很想了解完成順序。 我本來希望家屬按照他們添加的順序完成,但情況似乎並非如此。
特別是,這種行為令人驚訝:
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
{
var x = new CompletableFuture<Void>();
x.thenRun(() -> System.out.println(1));
x.thenRun(() -> System.out.println(2));
x.thenRun(() -> System.out.println(3));
x.complete(null);
}
{
var x = new CompletableFuture<Void>();
var y = x.copy();
y.thenRun(() -> System.out.println(1));
y.thenRun(() -> System.out.println(2));
y.thenRun(() -> System.out.println(3));
x.complete(null);
}
}
}
...導致以下 output ...
3
2
1
1
2
3
'x.thenRun()' 表達式生成的所有 3 個子期貨並行運行,因此您不能期望任何特定的打印數字順序。
'y.thenRun()' 也是如此。
表達的順序是一種實現特性,將來可能會改變,並且不受規范的支持。
所以你沒有鏈接那些thenRun
,因此對訂單有零保證,但你期望一些訂單? 對不起,這不是它的工作方式。
文檔沒有說明這種情況下的執行順序,所以無論您現在在 output 中看到什么:
使用當前設置通過代碼證明有點困難,但只需將其更改為:
var x = CompletableFuture.runAsync(() -> {
LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(1));
});
x.thenRun(() -> System.out.println(1));
x.thenRun(() -> System.out.println(2));
x.thenRun(() -> System.out.println(3));
x.join();
運行這個假設20 times
,我打賭至少一次,你不會看到3, 2, 1
,而是不同的東西。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.