Skip to main content
Executors and thread pools · Topic 5 of 7

Future and Callable

Definition​

A Callable is a task that returns a value (a Runnable does not). When you submit it to an executor you get a Future: a receipt you can use later to get the result with get(), which waits if it is not ready, or to see that the task failed.

Example code​

Submit tasks, then collect their results

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;

class Demo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);

Callable<Integer> square = () -> 7 * 7;
Future<Integer> answer = pool.submit(square);
System.out.println(answer.get()); // waits for the result

Future<Integer> failing = pool.submit(() -> { throw new IllegalStateException("boom"); });
try {
failing.get();
} catch (ExecutionException e) {
System.out.println("task failed with: " + e.getCause().getMessage());
}

List<Future<Integer>> all = pool.invokeAll(List.of(() -> 1, () -> 2, () -> 3)); // run several, wait for all
int total = 0;
for (Future<Integer> f : all) total += f.get();
System.out.println(total);
pool.shutdown();
}
}

// Output:
// 49
// task failed with: boom
// 6

Finished this page? Track your progress (saved only in your browser).