Executor InvokeAny First Success
invokeAny races the same request across worker tasks, returns the first success, cancels the rest, and throws ExecutionException only when every task fails.
Code
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();
}
}
}How it works
Count the class ReplicaRace as the entire surface area of Executor InvokeAny First Success.
IllegalStateException is thrown inside a try block — the matching handler clause, not any input check, decides what happens to it.
Using it
Running the file prints labeled results such as winner:, all failed -> — each operation’s effect is visible in the output.
Key statements
ExecutorService pool = Executors.newFixedThreadPool(3);
() -> { Thread.sleep(150); return "replica-ap"; }
() -> { throw new IllegalStateException("mirror down"); }
Interactive Tools for This Topic
FAQ
- Does the snippet validate its input?
- No — the `IllegalStateException` is raised inside a `try` block: execution reaches it unconditionally, and the surrounding handler clause decides what catches it. There is no input check in the snippet.
- What does Executor InvokeAny First Success print when run?
- Run it as a complete program — the output lines carry labels such as `winner:`, `all failed ->`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.