Skip to lesson

invokeAll and invokeAny

invokeAll runs a whole list of Callable tasks and waits until every one has finished. invokeAny runs the same kind of list but returns as soon as one task succeeds. Both are methods of ExecutorService, so the pool does the submitting and waiting for you.

Running a list of Callables with invokeAll

invokeAll runs a list of Callables and returns when all of them have finished. invokeAny returns the result of one task that succeeded and cancels the rest.

invokeAll(tasks) submits every Callable in the collection, waits until all of them have finished, and returns a List<Future<T>>. "Finished" includes failing with an exception.

Example 1 · Fee collected by four hostel blocks

HostelFeesDemo.javaJava
import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class HostelFeesDemo {    static Callable<Integer> blockTotal(int[] fees) {        return () -> {            int sum = 0;            for (int f : fees) {                sum += f;            }            return sum;        };    }
    public static void main(String[] args) throws Exception {        List<Callable<Integer>> tasks = List.of(                blockTotal(new int[] {45000, 45000, 42000}),                blockTotal(new int[] {38000, 40000}),                blockTotal(new int[] {45000, 45000, 45000, 30000}),                blockTotal(new int[] {50000}));
        ExecutorService pool = Executors.newFixedThreadPool(4);        List<Future<Integer>> results = pool.invokeAll(tasks);   // waits for all four
        int college = 0;        char block = 'A';        for (Future<Integer> f : results) {            System.out.println("Block " + block + ": Rs " + f.get());            college += f.get();            block++;        }        System.out.println("College total: Rs " + college);        pool.shutdown();    }}
Output
Block A: Rs 132000
Block B: Rs 78000
Block C: Rs 165000
Block D: Rs 50000
College total: Rs 425000

What this code does

  • blockTotal builds one Callable<Integer> per hostel block, in the order A, B, C, D. invokeAll runs the four on the pool and returns only when all are done.
  • Every future is already finished, so each get() returns at once. The list order matches the task order, so the first future is always Block A.

It saves you the usual loop of submit followed by a loop of get. When invokeAll returns, every future in the list is already done, so calling get() on them never blocks. The calling thread does wait inside invokeAll. Use it when you need the whole batch before you can go on, such as adding up the fee collected by every hostel block before printing the college total.

Collecting results in order

The list that invokeAll returns is in the same order as the tasks you passed in, not the order in which they finished. The third future always belongs to the third task, so you can match results to names by position.

Example 2 · Results in task order, whoever finishes first

OrderOfResultsDemo.javaJava
import java.util.ArrayList;import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class OrderOfResultsDemo {    static final List<String> finishOrder = new ArrayList<>();
    static Callable<Integer> trainFare(String city, int delayMs, int fare) {        return () -> {            Thread.sleep(delayMs);                      // a slow or fast fare server            synchronized (finishOrder) {                finishOrder.add(city);            }            if (fare < 0) {                throw new IllegalStateException("no trains to " + city);            }            return fare;        };    }
    public static void main(String[] args) throws InterruptedException {        List<String> cities = List.of("Chennai", "Delhi", "Goa", "Agra");        List<Callable<Integer>> tasks = List.of(                trainFare("Chennai", 300, 1450),                trainFare("Delhi", 10, 1820),                trainFare("Goa", 100, -1),                trainFare("Agra", 200, 1610));
        ExecutorService pool = Executors.newFixedThreadPool(4);        List<Future<Integer>> fares = pool.invokeAll(tasks);
        for (int i = 0; i < cities.size(); i++) {            try {                System.out.println(cities.get(i) + ": Rs " + fares.get(i).get());            } catch (ExecutionException e) {                System.out.println(cities.get(i) + ": " + e.getCause().getMessage());            }        }        synchronized (finishOrder) {            System.out.println("Finished in this order: " + finishOrder);        }        pool.shutdown();    }}
Output
Chennai: Rs 1450
Delhi: Rs 1820
Goa: no trains to Goa
Agra: Rs 1610
Finished in this order: [Delhi, Goa, Agra, Chennai]

What this code does

  • Delhi's server answered first and Chennai's last, yet fares.get(0) is still Chennai: the list follows the task order, so cities.get(i) and fares.get(i) always match.
  • Goa's task failed. Its future is in the list like the others, and its get() throws ExecutionException, which the loop handles without losing the other three fares.

A failed task still has its future in the list. Its get() throws ExecutionException, while the others return their values. So handle each future on its own: one bad task should not hide the good results.

invokeAny for the first successful answer

invokeAny(tasks) runs the tasks and returns the result (not a future) of one task that finished without an exception, usually the fastest one. The tasks that are still running are then cancelled.

Example 3 · Hall ticket from the fastest mirror

FastestMirrorDemo.javaJava
import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;import java.util.concurrent.atomic.AtomicBoolean;
public class FastestMirrorDemo {    static final AtomicBoolean slowMirrorStopped = new AtomicBoolean();
    static Callable<String> mirror(String name, int delayMs, boolean works) {        return () -> {            try {                Thread.sleep(delayMs);            } catch (InterruptedException e) {                slowMirrorStopped.set(true);           // cancelled by invokeAny                throw e;            }            if (!works) {                throw new IllegalStateException(name + " is down");            }            return "hall-ticket.pdf from " + name;        };    }
    public static void main(String[] args) throws Exception {        ExecutorService pool = Executors.newFixedThreadPool(3);
        List<Callable<String>> mirrors = List.of(                mirror("Mirror-Mumbai", 10, false),   // fastest, but broken                mirror("Mirror-Pune", 60, true),                mirror("Mirror-Delhi", 1000, true));  // works, but slow        System.out.println("Got: " + pool.invokeAny(mirrors));
        List<Callable<String>> allDown = List.of(                mirror("Mirror-X", 10, false),                mirror("Mirror-Y", 60, false));        try {            pool.invokeAny(allDown);        } catch (ExecutionException e) {            System.out.println("All mirrors failed, last error: " + e.getCause().getMessage());        }
        pool.shutdown();        pool.awaitTermination(5, TimeUnit.SECONDS);        System.out.println("Slow mirror was cancelled: " + slowMirrorStopped.get());    }}
Output
Got: hall-ticket.pdf from Mirror-Pune
All mirrors failed, last error: Mirror-Y is down
Slow mirror was cancelled: true

What this code does

  • Mumbai answered first but threw an exception, so invokeAny ignored it and waited for the next success: Pune. Delhi was still sleeping, so it was cancelled, and its InterruptedException set the flag.
  • When every task fails, invokeAny throws ExecutionException. Its cause is one of the failures, here the last one to arrive, so do not rely on which failure you get when several tasks fail.

It fits when several tasks can give the same answer and you only need one: download the same hall ticket from three mirror servers, or ask two payment gateways for the status of one UPI payment. Tasks that fail are ignored as long as another one succeeds. Only if every task fails does invokeAny throw an ExecutionException.

Timeouts on both

invokeAll(tasks, timeout, unit) waits at most that long. Tasks that have not finished by then are cancelled; their futures report isCancelled() as true, and get() on them throws CancellationException. The finished ones keep their results.

Example 4 · Time limits on invokeAll and invokeAny

BatchTimeoutDemo.javaJava
import java.util.List;import java.util.concurrent.Callable;import java.util.concurrent.CancellationException;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.TimeUnit;import java.util.concurrent.TimeoutException;
public class BatchTimeoutDemo {    static Callable<Integer> quote(int delayMs, int price) {        return () -> {            Thread.sleep(delayMs);            return price;        };    }
    public static void main(String[] args) throws Exception {        ExecutorService pool = Executors.newFixedThreadPool(3);        List<String> vendors = List.of("Alpha Print", "Beta Print", "Gamma Print");
        List<Future<Integer>> quotes = pool.invokeAll(List.of(                quote(20, 18000), quote(50, 15500), quote(2000, 12000)),                400, TimeUnit.MILLISECONDS);        for (int i = 0; i < quotes.size(); i++) {            Future<Integer> f = quotes.get(i);            try {                System.out.println(vendors.get(i) + ": Rs " + f.get());            } catch (CancellationException e) {                System.out.println(vendors.get(i) + ": no quote in time (cancelled: " + f.isCancelled() + ")");            }        }
        try {            pool.invokeAny(List.of(quote(400, 9000), quote(500, 9500)), 100, TimeUnit.MILLISECONDS);        } catch (TimeoutException e) {            System.out.println("invokeAny: no answer within 100 ms");        }        pool.shutdown();    }}
Output
Alpha Print: Rs 18000
Beta Print: Rs 15500
Gamma Print: no quote in time (cancelled: true)
invokeAny: no answer within 100 ms

What this code does

  • The college fest committee waits 400 ms for printing quotes. Two vendors answered in time; the third was cancelled, and get() on its future throws CancellationException instead of blocking.
  • Both invokeAny tasks need at least 400 ms, so after 100 ms it throws TimeoutException and cancels them.

invokeAny(tasks, timeout, unit) throws TimeoutException if no task has succeeded in time, and cancels the rest. The timeout covers the whole batch, not each task. A 100 ms limit means "everything I get within 100 ms from now".

Choosing invokeAll, invokeAny or submit

All three run tasks on the pool. Pick by what you need back.

  • invokeAll: you need every result, such as totals from all blocks or prices from all shops. You get futures in task order.
  • invokeAny: any one correct answer is enough, such as the fastest mirror. You get a plain value.
  • submit in a loop: you want to keep working while tasks run, or handle each result as soon as it arrives.
  • Add a timeout whenever a slow task must not hold up the whole program.

Next step

Check your understanding

12 quick questions