applyToEither 怎么使用
applytoeither 用于在两个 completablefuture 中,谁先完成就执行谁的转换逻辑并返回结果。调用时传入另一个 completablefuture 和一个 function,该函数仅对获胜方的结果生效,最终返回一个包含转换后结果的 completablefuture。

如何结合超时处理实现竞速
通过 orTimeout 或 completeOnTimeout 配合 applyToEither 可以实现竞速逻辑。将主任务与超时任务(如抛出异常或返回默认值)进行竞争,确保程序不会无限期等待。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class RaceExample {
public static void main(String[] args) throws Exception {
CompletableFuture<String> slowTask = CompletableFuture.supplyAsync(() -> {
try { TimeUnit.SECONDS.sleep(3); } catch (InterruptedException e) {}
return "Slow Result";
});
CompletableFuture<String> fastFallback = CompletableFuture.completedFuture("Fast Fallback");
// 慢任务如果超过1秒未完成,fastFallback 会立即触发
CompletableFuture<String> result = slowTask
.orTimeout(1, TimeUnit.SECONDS)
.applyToEither(fastFallback, r -> r);
System.out.println(result.get()); // 输出: Fast Fallback
}
}
基于输入条件判断的具体问题
当两个任务都成功完成时,applyToEither 只执行第一个完成的任务对应的 Function,另一个任务的结果会被丢弃。如果第一个完成的任务抛出异常,整个链式调用将变为异常状态。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class EitherLogic {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<Integer> taskA = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(500); } catch (InterruptedException e) {}
return 10;
});
CompletableFuture<Integer> taskB = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) {}
return 20;
});
// taskB 先完成,applyToEither 使用 taskB 的结果 20
// 即使 taskA 稍后完成,其结果也不会被应用
CompletableFuture<Integer> winner = taskA.applyToEither(taskB, val -> val * 2);
System.out.println(winner.get()); // 输出: 40
}
}


















