00:00

Future Interface in Java: Results, Timeouts and Cancellation

Last updated:

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

Future interface hierarchyRunnableFuture and ScheduledFuture extend Future. CompletableFuture implements Future. FutureTask implements RunnableFuture.«interface»Future<V>this pageget(), get(timeout, unit)cancel(boolean)isDone(), isCancelled()state(), resultNow() †† added in Java 19«interface»RunnableFuture<V>run()«interface»ScheduledFuture<V>getDelay(unit)«class»CompletableFuture<T>thenApply(…), join()«class»FutureTask<V>FutureTask(Callable)extendsimplementsinterfaceclass

Swipe sideways to see the whole diagram.

  • RunnableFuture (interface): A Future that is also a Runnable; executors use it to wrap submitted tasks.
  • ScheduledFuture (interface): Returned by scheduled executors; adds getDelay().
  • CompletableFuture (class): A Future you can complete manually and chain with callbacks.
  • FutureTask (class): The standard implementation returned by submit().
  • ForkJoinTask (abstract class): Also implements Future (not shown), for fork/join tasks.

3. Method Details

MethodDescription
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

CreditCheckTimeout.java
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());
        }
    }
}
Output
No answer within 300 ms, cancelling the check
cancel() returned: true
isDone: true, isCancelled: true
state(): CANCELLED

How the code works

  1. get(300, MILLISECONDS) waits at most 300 ms, then throws TimeoutException. The task keeps running; a timeout does not stop it.
  2. cancel(true) interrupts the worker thread, which wakes the task from Thread.sleep().
  3. After cancellation, isDone() and isCancelled() are both true, and state() reports CANCELLED.
  4. Calling get() now would throw CancellationException.

5. Example: Inspecting Finished Futures (Java 19+)

FutureStateDemo.java
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");
                }
            }
        }
    }
}
Output
lookup 1: 42 units
lookup 2: failed - unknown SKU
lookup 3: 0 units

How the code works

  1. invokeAll() returns only when all three lookups have completed, so every Future is finished.
  2. state() tells you how each one ended, and a switch expression handles all four Future.State values.
  3. resultNow() and exceptionNow() return immediately, without the checked exceptions of get().
  4. Calling resultNow() on a failed future, or exceptionNow() on a successful one, throws IllegalStateException, 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 with get() or use CompletableFuture callbacks.

7. Summary

  • A Future<V> is a handle to a result that may not be ready yet.
  • get() waits; the timed version throws TimeoutException but leaves the task running.
  • cancel(true) interrupts a running task; afterwards isDone() and isCancelled() are true.
  • Java 19 added state(), resultNow() and exceptionNow().

Related Tutorials

8. References