accepteither 用于等待两个异步任务中先完成的那个,并执行一个消费型操作。它不返回新值,而是对先完成的 future 的结果调用传入的 action。如果两个任务都抛出异常,只有先抛出的那个会被捕获并处理;若先完成的任务正常结束,则忽略另一个任务的异常。

如何获取先完成任务的结果
使用 thenAcceptBoth 可以获取两个任务都完成后的结果,而 acceptEither 只关心谁先跑完。如果你需要的是“二选一”的逻辑,比如优先用缓存数据,缓存没好就用网络数据,那么 acceptEither 是更合适的选择。它接受两个 CompletableFuture 和一个 Consumer<t></t>,其中 T 是两个任务返回值的公共父类或接口。

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
public class AcceptEitherDemo {
public static void main(String[] args) throws ExecutionException, InterruptedException {
CompletableFuture<String> fastTask = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(100); } catch (InterruptedException e) {}
return "Fast Result";
});
CompletableFuture<String> slowTask = CompletableFuture.supplyAsync(() -> {
try { Thread.sleep(500); } catch (InterruptedException e) {}
return "Slow Result";
});
// acceptEither: 谁先完成就执行 action
CompletableFuture<Void> resultFuture = fastTask.acceptEither(slowTask, res -> {
System.out.println("Winner: " + res);
});
// 等待动作执行完毕
resultFuture.get();
}
}
如何处理 acceptEither 中的异常
当先完成的任务抛出异常时,acceptEither 不会自动吞掉异常,而是将异常传递给下游。如果希望优雅降级,可以在调用链后追加 exceptionally。注意,acceptEither 本身返回的是 CompletableFuture<void></void>,所以异常处理必须接在它后面,或者在传入的 Consumer 内部 try-catch。
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
立即学习“Java免费学习笔记(深入)”;

import java.util.concurrent.CompletableFuture;
public class ExceptionHandlingDemo {
public static void main(String[] args) {
CompletableFuture<String> taskA = CompletableFuture.supplyAsync(() -> {
throw new RuntimeException("Task A failed");
});
CompletableFuture<String> taskB = CompletableFuture.supplyAsync(() -> "Task B Success");
// 即使 A 失败,B 成功,也会执行 B 的 action
taskA.acceptEither(taskB, res -> {
System.out.println("Executed with: " + res);
}).exceptionally(ex -> {
// 只有当两个任务都失败,或者先失败的那个没有对应的成功任务时才会进入
System.err.println("Exception handled: " + ex.getMessage());
return null;
});
}
}
acceptEither 与 supplyEither 的区别是什么
acceptEither 返回 CompletableFuture<void></void>,仅用于副作用(如打印、写库),不产生新值。如果需要基于先完成的任务结果继续计算,应使用 supplyEither(Java 9+)或 applyToEither(Java 8)。前者返回 CompletableFuture<r></r>,允许链式调用。例如:task.applyToEither(other, r -> r.toUpperCase()) 会返回转换后的字符串。选择哪个取决于你是否需要后续处理先完成任务的输出。

















