Callable and Future in Java: Task Results, Timeouts, Cancellation and invokeAll
How to get results and errors back from tasks run by an executor: Callable versus Runnable, Future.get with and without a timeout, ExecutionException, cancel(true), the Java 19 state/resultNow/exceptionNow methods, invokeAll, invokeAny and ExecutorCompletionService, verified on JDK 25.
kvi5hnuCode Sprout team member6 min readOn this page
MiniPool from article 19 could only run Runnables: tasks that return nothing and can't throw checked exceptions. Real work usually produces a result or fails. The executor framework handles that with two interfaces: Callable, a task that returns a value, and Future, a handle to a result that may not exist yet.
Callable versus Runnable
public interface Runnable {
void run();
}
public interface Callable<V> {
V call() throws Exception;
}
Both are functional interfaces, so lambdas work for either. The compiler picks Callable when the lambda returns a value. A lambda with a void body is a Runnable, which can't throw checked exceptions; add return null; to make it a Callable. executor.submit(() -> findFlight()) gives you a Future<Flight>, and executor.submit(() -> log("x")) gives you a Future<?> that completes with null.
Future: a handle to a result
submit returns immediately with a Future. The task runs on a pool thread or a virtual thread, and the Future lets the caller:
| Method | What it does |
|---|---|
get() | waits until the task finishes, then returns its result or throws |
get(timeout, unit) | the same, but throws TimeoutException if it's not done in time |
isDone() | true once the task has finished in any way |
cancel(mayInterruptIfRunning) | cancels the task. With true, a running task is interrupted |
isCancelled() | whether it was cancelled |
state() (Java 19+) | RUNNING, SUCCESS, FAILED or CANCELLED |
resultNow() / exceptionNow() (Java 19+) | the result or exception of a finished task, without blocking or checked exceptions. They throw IllegalStateException if the task isn't in the matching state |

Everything in one program
The program runs the course's trip-quote calls as Callables on a virtual-thread executor and shows every way a Future can end:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
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;
import java.util.concurrent.atomic.AtomicBoolean;
public class Solution {
record Flight(String route, int price) {}
record Hotel(String name, int price) {}
static void waitFor(long ms) throws InterruptedException { Thread.sleep(ms); }
static Flight findFlight() throws InterruptedException { waitFor(100); return new Flight("Oslo-Lisbon", 240); }
static Hotel findHotel() throws InterruptedException { waitFor(100); return new Hotel("Casa Azul", 360); }
static Hotel findHotelBroken() throws InterruptedException {
waitFor(50);
throw new IllegalStateException("hotel service returned 503");
}
static long since(long start) { return Math.round((System.nanoTime() - start) / 1e8) * 100; }
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
// 1. Two Callables in parallel; get() waits for each result
long start = System.nanoTime();
Future<Flight> flight = executor.submit(Solution::findFlight);
Future<Hotel> hotel = executor.submit(Solution::findHotel);
System.out.println("1. total " + (flight.get().price() + hotel.get().price())
+ " after about " + since(start) + " ms");
// 2. A task's exception comes back wrapped in ExecutionException
Future<Hotel> broken = executor.submit(Solution::findHotelBroken);
try {
broken.get();
} catch (ExecutionException e) {
System.out.println("2. failed: " + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage());
}
System.out.println(" state=" + broken.state() + ", exceptionNow=" + broken.exceptionNow().getMessage());
// 3. A timeout doesn't stop the task; cancel(true) interrupts it
AtomicBoolean sawInterrupt = new AtomicBoolean();
Future<String> slow = executor.submit(() -> {
try { waitFor(5_000); return "late"; }
catch (InterruptedException e) { sawInterrupt.set(true); throw e; }
});
try {
slow.get(100, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
System.out.println("3. timed out; still running? " + (slow.state() == Future.State.RUNNING));
}
slow.cancel(true);
Thread.sleep(50);
System.out.println(" after cancel(true): state=" + slow.state() + ", task saw interrupt=" + sawInterrupt.get());
// 4. invokeAll waits for all, results in submission order
List<Callable<Integer>> prices = List.of(() -> { waitFor(150); return 240; },
() -> { waitFor(50); return 360; },
() -> { waitFor(100); return 35; });
start = System.nanoTime();
List<Integer> all = new ArrayList<>();
for (Future<Integer> f : executor.invokeAll(prices)) all.add(f.resultNow());
System.out.println("4. invokeAll " + all + " after about " + since(start) + " ms");
// 5. invokeAny returns the first successful result and cancels the rest
List<Callable<String>> mirrors = List.of(() -> { waitFor(300); return "mirror A"; },
() -> { waitFor(100); return "mirror B"; },
() -> { throw new IllegalStateException("mirror C down"); });
start = System.nanoTime();
System.out.println("5. invokeAny -> " + executor.invokeAny(mirrors) + " after about " + since(start) + " ms");
// 6. CompletionService hands results back in completion order
CompletionService<Integer> done = new ExecutorCompletionService<>(executor);
for (Callable<Integer> c : prices) done.submit(c);
List<Integer> inOrder = new ArrayList<>();
for (int i = 0; i < prices.size(); i++) inOrder.add(done.take().get());
System.out.println("6. completion order " + inOrder);
}
}
}
Output (times are rounded to 100 ms and may differ slightly):
1. total 600 after about 100 ms
2. failed: IllegalStateException: hotel service returned 503
state=FAILED, exceptionNow=hotel service returned 503
3. timed out; still running? true
after cancel(true): state=CANCELLED, task saw interrupt=true
4. invokeAll [240, 360, 35] after about 200 ms
5. invokeAny -> mirror B after about 100 ms
6. completion order [360, 35, 240]
Results and failures
- Parallel results. Both calls ran at the same time, so getting both took about 100 ms, not 200.
get()blocks the caller, and only until that particular result is ready. On a virtual thread that wait is cheap: it unmounts. - Failures are wrapped. An exception thrown by
call()is stored in theFuture, andget()rethrows it inside anExecutionException. The original exception isgetCause(). Code that only catchesExecutionExceptionand logse.getMessage()prints something likejava.lang.IllegalStateException: hotel service returned 503, so use the cause for clear error messages and for deciding what to do.
A related trap: when you submit a task and never call get(), its exception is silently lost. The Future holds it, and nobody looks. execute(runnable) doesn't have this problem, because the exception reaches the thread's uncaught-exception handler, but then there's no result either. Always either get() the futures you submit or handle errors inside the task.
Timeouts and cancellation
- A timeout is the caller giving up, not the task stopping. After
get(100, MILLISECONDS)threwTimeoutException, the task was stillRUNNING. To stop it, callcancel(true), which interrupts the thread running it. The task saw the interrupt insleepand ended.cancel(false)would only prevent a task that hasn't started from running.
Cancellation is cooperative. cancel(true) interrupts, and code that blocks in interruptible calls (sleep, BlockingQueue.take, socket reads on virtual threads) stops promptly. A loop that never checks Thread.interrupted() keeps running even though its Future already says CANCELLED.
Working with many tasks
invokeAll(tasks)submits all of them and waits until all are done. It returns the futures in submission order, so the slowest task, 150 ms here, determines the total time. The program prints it as about 200 ms because it rounds to the nearest 100 ms. An overload with a timeout cancels whatever hasn't finished in time.invokeAny(tasks)returns the result of the first task to succeed and cancels the others. Failed tasks are ignored unless all fail, in which case it throwsExecutionException. It's handy for querying redundant mirrors or replicas.ExecutorCompletionServicewraps an executor and puts each finishedFutureonto a queue.take()returns futures in completion order, so you can process each result as soon as it's ready instead of waiting for the slowest.
Limits of Future
Future is a simple, blocking handle. It can't attach a callback ("when done, do X"), combine two futures without blocking a thread, or express "cancel the others if one fails" in general. CompletableFuture (article 6) adds composition, and structured concurrency (Part 4) adds lifetimes and failure policies to groups of subtasks. With virtual threads, the simple blocking style of Future.get() becomes practical again, and structured concurrency builds on exactly that.
What's current
- Java 19 added
Future.state(),resultNow()andexceptionNow(), along withExecutorService.close(). - With virtual threads, blocking on
get()costs almost nothing, so the straightforward submit-then-get style scales. - In structured concurrency,
forkreturns aSubtaskrather than aFuture, with similarstate()andget()methods but a scope-managed lifetime (Part 4).
Common questions
What's the difference between execute and submit?
execute(Runnable) returns nothing, and exceptions go to the thread's uncaught-exception handler. submit accepts Runnable or Callable and returns a Future that captures the result or exception.
Does isDone() mean the task succeeded?
No. It's true for success, failure and cancellation alike. Use state() to distinguish them.
What happens if I call get() on a cancelled Future?
It throws CancellationException, an unchecked exception.
Can get() itself be interrupted?
Yes. If the waiting thread is interrupted, get() throws InterruptedException. The task keeps running. Cancel it explicitly if it's no longer needed.
Summary
Callable<V>returns a value and may throw.submitreturns aFuture<V>immediately.get()waits for the result and rethrows task failures asExecutionException, with the original as the cause.get(timeout)throwsTimeoutExceptionbut doesn't stop the task.cancel(true)interrupts it, and cooperative code then stops.- Java 19's
state(),resultNow()andexceptionNow()inspect a finishedFuturewithout blocking. invokeAllwaits for all tasks,invokeAnyreturns the first success, andExecutorCompletionServicedelivers results in completion order.- A submitted task whose
Futureis never checked loses its exception silently.
Practice questions
What does this print?
try (ExecutorService ex = Executors.newVirtualThreadPerTaskExecutor()) {
Future<Integer> f = ex.submit(() -> Integer.parseInt("abc"));
try {
f.get();
} catch (ExecutionException e) {
System.out.println(e.getCause().getClass().getSimpleName());
}
}
Answer
NumberFormatException. The task's exception is stored in the Future, and get() throws an ExecutionException whose cause is the original exception.
A service calls future.get(2, SECONDS) on a slow remote lookup and returns a fallback on TimeoutException. Under load, the number of busy threads keeps growing. Why?
Answer
The timeout only stops the caller from waiting. The lookups keep running, each holding a thread (and a connection) until they finish. Cancel the future in the timeout handler with future.cancel(true), and give the remote call its own timeout, so abandoned work actually stops.
You need to show search results to a user as soon as each of five providers answers. Which tool fits best: invokeAll, invokeAny or ExecutorCompletionService?
Answer
ExecutorCompletionService. It hands back each result as soon as that task finishes. invokeAll would wait for the slowest provider before returning anything, and invokeAny would return only one result.
Previous: ThreadPoolExecutor in Java: Core and Maximum Size, Work Queues and Rejection Policies
Next: ForkJoinPool in Java: Work Stealing, RecursiveTask and Why Ordinary Pools Deadlock

More in Modern Java Concurrency
Quiz: Java Concurrency Changes From Java 21 to Java 28
Sixteen questions on what changed release by release: virtual threads final in 21, synchronized without pinning in 24, scoped values final in 25, and the long road of structured concurrency from subclasses to open() and Joiner, the Java 26 and 27 refinements, and final in 28.
Quiz: Java Concurrency's Delicate Details
Twenty edge cases of modern Java concurrency that surprise experienced developers: virtual thread priorities and names, semaphores without owners, null scoped values, cancelling a CompletableFuture, pool sizing with unbounded queues, and StructuredTaskScope's strict rules.
Quiz: Java Concurrency Interview Questions (Virtual Threads, Structured Concurrency, Scoped Values)
Twenty questions of the kind interviewers ask about modern Java concurrency: platform vs virtual threads, pinning, pools and limits, CompletableFuture, structured concurrency, scoped values vs ThreadLocal, reactive programming, and production diagnostics.
Quiz: Modern Java Concurrency Final Exam (All 7 Parts)
The final exam for the modern Java concurrency course: thirty questions across all seven parts, from platform threads, pools and CompletableFuture through virtual threads, the scheduler, structured concurrency, scoped values, reactive streams and frameworks.
Discussion
Sign in to ask a question or share what you learned.