简体   繁体   English

Java CompletableFuture applyToEither 方法对第一个完成的未来进行操作还是从两个中随机选择一个?

[英]Java CompletableFuture applyToEither method operates on the first completed future or randomly chooses one from two?

From Oracle document: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/CompletionStage.html#applyToEither(java.util.concurrent.CompletionStage,java.util.function.Function) From Oracle document: https://docs.oracle.com/javase/10/docs/api/java/util/concurrent/CompletionStage.html#applyToEither(java.util.concurrent.CompletionStage,java.util.function.Function)

applyToEither

<U> CompletionStage<U> applyToEither(CompletionStage<? extends T> other, Function<? super T,U> fn)

Returns a new CompletionStage that, when either this or the other given stage complete normally, is executed with the corresponding result as argument to the supplied function.返回一个新的 CompletionStage,当这个或另一个给定阶段正常完成时,将使用相应的结果作为提供的 function 的参数执行。 See the CompletionStage documentation for rules covering exceptional completion.有关异常完成的规则,请参阅 CompletionStage 文档。

It says it applies to "either this or the other", which I think is not clear.它说它适用于“这个或另一个”,我认为这还不清楚。 I wonder whether it chooses the first completed future or just randomly picks up one from the two?我想知道它是选择第一个完成的未来还是只是从两者中随机选择一个?

It chooses the first completed future.它选择第一个完成的未来。

CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> task("Peter", 100)); // Generate "Peter", sleep 100ms
CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> task("John", 200)); // Generate "John", sleep 200ms

CompletableFuture<Void> future3 = future2.acceptEither(future1, (text) -> {
  Truth.assertThat(text).isEqualTo("Peter"); // Expected value is "Peter" from future1   
});

future3.get()

The result is the same as swapped future variables:结果与交换的未来变量相同:

CompletableFuture<Void> future3 = future1.acceptEither(future2, (text) -> {
  Truth.assertThat(text).isEqualTo("Peter"); // Expected value is "Peter" from future1   
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM