← 中文资源

简体中文版本

Executor invokeAny 首个成功

把同一请求发给多个副本,invokeAny 返回最先成功者的结果并取消其余任务;只有全部失败才抛 ExecutionException,适合副本竞速与快速回源。

阅读英文原文

实现说明

逻辑集中在类 ReplicaRace里。 IllegalStateException 在 try 块内抛出——谁来接住由匹配的 except 子句决定,与任何输入检查无关。

使用要点

  • 演示输出是带标签的(winner:、all failed ->),每个操作都会留下自己的一行标注。

常见问题

这个示例会校验输入吗?

不会——IllegalStateException 在 try 块内抛出:执行到这一行就必然抛出,由外围的 except 子句决定谁来接住。示例里没有输入校验。

运行「Executor invokeAny 首个成功」会打印什么?

不用做任何设置,直接把文件跑完——输出里的 winner:、all failed -> 标签标明各步骤。

核心语句

ExecutorService pool = Executors.newFixedThreadPool(3);
() -> { Thread.sleep(150); return "replica-ap"; }
() -> { throw new IllegalStateException("mirror down"); }

代码示例

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ReplicaRace {

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        try {
            // Same request sent to three replicas: invokeAny returns the first success and cancels the rest
            String winner = pool.invokeAny(List.of(
                    () -> { Thread.sleep(300); return "replica-eu"; },
                    () -> { Thread.sleep(80);  return "replica-us"; },
                    () -> { Thread.sleep(150); return "replica-ap"; }
            ));
            System.out.println("winner: " + winner);

            // When all fail it throws ExecutionException whose cause explains why
            try {
                pool.invokeAny(List.of(
                        () -> { throw new IllegalStateException("mirror down"); }
                ));
            } catch (ExecutionException e) {
                System.out.println("all failed -> " + e.getCause().getMessage());
            }
        } finally {
            pool.shutdownNow();
        }
    }
}