Multithreading: invokeAny returns the first result and cancels the rest

invokeAny submits every task but only waits for one of them to succeed, returning that single value and cancelling the tasks that are still running. It is useful when several strategies can answer the same question and only the quickest one matters.

Code
ExecutorService pool = Executors.newFixedThreadPool(2);
List<Callable<String>> tasks = List.of(
    () -> { Thread.sleep(60); return "slow"; },
    () -> "fast"
);
String winner = pool.invokeAny(tasks);
pool.shutdown();
System.out.println("Winner: " + winner);
Output
Winner: fast
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms