CompletableFuture AnyOf Fastest Race

Race several async sources with CompletableFuture.anyOf: the first to complete wins, the returned Object result needs one cast back.

JavaData Fetching

Code

snippet
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class MirrorRace {

    public static void main(String[] args) throws Exception {
        // 三个镜像源:延迟不同,先到先得
        List<CompletableFuture<String>> mirrors = List.of(
                CompletableFuture.supplyAsync(() -> {
                    sleep(120);
                    return "mirror-a";
                }),
                CompletableFuture.supplyAsync(() -> {
                    sleep(40);
                    return "mirror-b";
                }),
                CompletableFuture.supplyAsync(() -> {
                    sleep(200);
                    return "mirror-c";
                }));

        // anyOf 接受 CompletableFuture<?>...:任一完成即完成
        CompletableFuture<Object> winner =
                CompletableFuture.anyOf(mirrors.toArray(new CompletableFuture[0]));

        // 结果类型是 Object:完成时已确定是 String,一次 cast 拿回
        String result = (String) winner.join();
        System.out.println("first response = " + result);

        // 输家不再等待:演示结束后一并释放
        for (CompletableFuture<String> mirror : mirrors) {
            mirror.cancel(true);
        }
    }

    static void sleep(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

How it works

CompletableFuture AnyOf Fastest Race reduces to the class MirrorRace and the function sleep.

The one repetition in this snippet is the loop for (CompletableFuture<String> mirror : mirrors).

Putting it to use

The signature you will reach for first is static void sleep(long millis)

The demo output is labeled (first response =), so the printed lines read as a trace of the operations that ran.

Launch the file; main takes over and steps through sleep.

Core lines

CompletableFuture.anyOf(mirrors.toArray(new CompletableFuture[0]));
for (CompletableFuture<String> mirror : mirrors) {
mirror.cancel(true);
}
CompletableFuture.supplyAsync(() -> {
sleep(120);
return "mirror-a";
}),

FAQ

What does CompletableFuture AnyOf Fastest Race print when run?
Run it as a complete program — the output lines carry labels such as `first response =`.