Future Interface in Java: Results, Timeouts and Cancellation
A Future represents the result of a computation that may not have finished yet. Every time you submit a task to an executor, you get a Future back, and you use it to wait for the result, check progress or cancel the task.
This tutorial covers all of its methods, including the Java 19 additions, with examples of timeouts, cancellation and failure handling.
1. What Is the Future Interface?
Future<V> is a generic interface in java.util.concurrent, added in Java 5. V is the type of the result. A Future starts out incomplete; it completes once, when the task finishes normally, throws an exception, or is cancelled.
It is a read-only view of the task: you cannot set its value directly. For a future you complete yourself, see CompletableFuture.
2. Future Interface Hierarchy
Swipe sideways to see the whole diagram.
RunnableFuture(interface): A Future that is also aRunnable; executors use it to wrap submitted tasks.ScheduledFuture(interface): Returned by scheduled executors; addsgetDelay().CompletableFuture(class): A Future you can complete manually and chain with callbacks.FutureTask(class): The standard implementation returned bysubmit().ForkJoinTask(abstract class): Also implements Future (not shown), for fork/join tasks.
3. Method Details
| Method | Description |
|---|---|
V get() | Waits for the result. Throws ExecutionException if the task failed, CancellationException if it was cancelled. |
V get(timeout, unit) | Like get(), but throws TimeoutException if the result is not ready in time. |
boolean cancel(mayInterrupt) | Attempts to cancel; true interrupts the thread if the task is already running. |
boolean isDone() | true once the task has completed in any way, including cancellation. |
boolean isCancelled() | true if the task was cancelled before finishing normally. |
State state() | Java 19+: RUNNING, SUCCESS, FAILED or CANCELLED. |
V resultNow() | Java 19+: the result without waiting; throws if the task did not succeed. |
Throwable exceptionNow() | Java 19+: the exception without waiting; throws if the task did not fail. |
4. Example: Timing Out and Cancelling a Slow Task
import java.util.concurrent.ExecutionException;
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 CreditCheckTimeout {
public static void main(String[] args) throws InterruptedException, ExecutionException {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<String> creditCheck = executor.submit(() -> {
Thread.sleep(5_000); // the credit bureau is very slow today
return "APPROVED";
});
try {
String decision = creditCheck.get(300, TimeUnit.MILLISECONDS);
System.out.println("Decision: " + decision);
} catch (TimeoutException e) {
System.out.println("No answer within 300 ms, cancelling the check");
boolean cancelled = creditCheck.cancel(true); // interrupt the running task
System.out.println("cancel() returned: " + cancelled);
}
System.out.println("isDone: " + creditCheck.isDone() + ", isCancelled: " + creditCheck.isCancelled());
System.out.println("state(): " + creditCheck.state());
}
}
}
No answer within 300 ms, cancelling the check cancel() returned: true isDone: true, isCancelled: true state(): CANCELLED
How the code works
get(300, MILLISECONDS)waits at most 300 ms, then throwsTimeoutException. The task keeps running; a timeout does not stop it.cancel(true)interrupts the worker thread, which wakes the task fromThread.sleep().- After cancellation,
isDone()andisCancelled()are bothtrue, andstate()reportsCANCELLED. - Calling
get()now would throwCancellationException.
5. Example: Inspecting Finished Futures (Java 19+)
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
// Java 19+: state(), resultNow() and exceptionNow() inspect a finished Future without try/catch around get()
public class FutureStateDemo {
public static void main(String[] args) throws InterruptedException {
List<Callable<Integer>> stockLookups = List.of(
() -> 42, // in stock
() -> { throw new IllegalArgumentException("unknown SKU"); },
() -> 0); // sold out
try (ExecutorService executor = Executors.newFixedThreadPool(3)) {
List<Future<Integer>> results = executor.invokeAll(stockLookups);
for (int i = 0; i < results.size(); i++) {
Future<Integer> f = results.get(i);
switch (f.state()) {
case SUCCESS -> System.out.println("lookup " + (i + 1) + ": " + f.resultNow() + " units");
case FAILED -> System.out.println("lookup " + (i + 1) + ": failed - " + f.exceptionNow().getMessage());
case CANCELLED -> System.out.println("lookup " + (i + 1) + ": cancelled");
case RUNNING -> System.out.println("lookup " + (i + 1) + ": still running");
}
}
}
}
}
lookup 1: 42 units lookup 2: failed - unknown SKU lookup 3: 0 units
How the code works
invokeAll()returns only when all three lookups have completed, so every Future is finished.state()tells you how each one ended, and a switch expression handles all fourFuture.Statevalues.resultNow()andexceptionNow()return immediately, without the checked exceptions ofget().- Calling
resultNow()on a failed future, orexceptionNow()on a successful one, throwsIllegalStateException, which is why the code checks the state first.
6. Common Mistakes and Best Practices
- Blocking forever. Plain
get()has no limit; use the timed overload for anything that calls a remote service. - Assuming a timeout cancels the task. It does not. Call
cancel(true)if the work is no longer wanted. - Ignoring the cause. The real error is
ExecutionException.getCause(). - Tasks that ignore interrupts. cancel(true) can only stop a task that checks for interruption or calls a blocking method.
- Polling
isDone()in a loop. It wastes CPU; block withget()or useCompletableFuturecallbacks.
7. Summary
- A
Future<V>is a handle to a result that may not be ready yet. get()waits; the timed version throwsTimeoutExceptionbut leaves the task running.cancel(true)interrupts a running task; afterwardsisDone()andisCancelled()aretrue.- Java 19 added
state(),resultNow()andexceptionNow().
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. Does Future.get() with a timeout cancel the task?
No. get(timeout, unit) only stops waiting and throws TimeoutException. The task keeps running until it finishes or you call cancel().
Q2. What does cancel(true) do compared with cancel(false)?
Both prevent a task that has not started from running. With true, a task that is already running is also interrupted; with false, a running task is allowed to finish.
Q3. Why does get() throw ExecutionException?
Because the task itself threw an exception. The executor stores it, and get() rethrows it wrapped in ExecutionException; call getCause() to see the original.
Q4. What are the values of Future.State?
RUNNING, SUCCESS, FAILED and CANCELLED. The enum and the state() method were added in Java 19.
Q5. Is isDone() true for a cancelled or failed task?
Yes. isDone() returns true once the task has completed for any reason: normal completion, an exception, or cancellation.