在 completionstage.applytoeitherasync 中,可以直接传入一个实现了 java.util.function.function 的函数式接口实例。该方法的签名要求第一个参数是另一个 completionstage,第二个参数是一个 function super t, ? extends u>。当两个阶段竞争完成时,如果当前阶段先完成,则应用该函数并返回结果;如果对手阶段先完成,则直接传递其结果(不应用函数)。例如,使用 lambda 表达式 (value) -> value.touppercase() 即可将字符串转换为大写。

如何定义并传入 Function 参数
要使用 applyToEitherAsync,你需要确保你的函数符合 Function 接口的规范,即接收一个输入并返回一个输出。你可以使用 Lambda 语法或方法引用。关键在于理解这个函数只会在“当前”阶段获胜时被调用。如果对手阶段赢了,函数会被忽略,对手的结果会直接流向后续链。以下代码展示了如何创建一个异步任务,并在其中使用 Lambda 来转换结果。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ApplyToEitherExample {
public static void main(String[] args) {
Executor executor = Executors.newFixedThreadPool(2);
// 创建两个竞争的阶段
CompletableFuture<string> stageA = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) {}
return "Result A";
}, executor);
CompletableFuture<string> stageB = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(50); } catch (InterruptedException e) {}
return "Result B";
}, executor);
// applyToEitherAsync: 如果 stageA 先完成,对 stageA 的结果应用 function
// 如果 stageB 先完成,直接返回 stageB 的结果,function 不被执行
CompletableFuture<string> result = stageA.applyToEitherAsync(stageB,
(input) -> {
System.out.println("Function applied to: " + input);
return input.toUpperCase();
}, executor);
result.thenAccept(System.out::println);
}
}</string></string></string>
运行上述代码,由于 stageB 睡眠更短,它通常会先完成。因此控制台只会打印最终结果(如 RESULT B),而不会打印 “Function applied to...”。如果修改 stageA 使其更快,则会看到函数被应用且结果为 RESULT A。
Function 类型推断与返回值处理
在使用 applyToEitherAsync 时,类型推断至关重要。函数的输入类型必须与两个竞争阶段的泛型类型兼容,或者能够被自动转换。通常,两个竞争阶段应具有相同的泛型类型 T,这样 Function 才能明确工作。如果类型不一致,编译器可能会报错或需要显式类型声明。此外,返回值类型 R 决定了新 CompletionStage 的类型。如果函数抛出异常,该异常将被封装在返回的 CompletionStage 中,导致其进入异常状态。
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class TypeInferenceExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<integer> future1 = CompletableFuture.completedFuture(10);
CompletableFuture<integer> future2 = CompletableFuture.completedFuture(20);
// 这里的 Function 接收 Integer,返回 String
CompletableFuture<string> transformed = future1.applyToEitherAsync(future2,
(num) -> "Number is: " + num
);
// 验证结果:取决于哪个 Future 先完成(这里都是同步完成的,所以看实现细节,通常取第一个准备好的)
// 注意:completedFuture 是立即完成的,applyToEither 的行为在非异步竞争场景下可能表现为取第一个
String result = transformed.get();
System.out.println(result);
}
}</string></integer></integer>
在这个例子中,future1 和 future2 都是立即完成的。在实际异步场景中,谁先触发完成回调,谁就决定路径。函数 (num) ->
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











