Future
A Future is a receipt for a result that does not exist yet. You get it the moment you submit a task, and later you use it to wait for the value, check whether the task finished, or cancel it.
Detailed Explanation
Submitting work to a pool creates a timing problem. The task runs on another thread, so the calling thread cannot use a plain return value; by the time submit returns, nothing has been computed. Future<T> closes that gap. It is a small object shared between the two threads: the worker writes the result into it, and whoever holds it can read the result out.
The interface is deliberately narrow. get() blocks the calling thread until the task completes, then returns the value. get(timeout, unit) blocks for at most that long and throws TimeoutException instead of hanging. isDone() tells you whether the task has finished, whether by success, failure, or cancellation. cancel(mayInterruptIfRunning) tries to stop it.
Cancellation is weaker than it looks. If the task has not started, it is removed from the queue and never runs. If it is already running, cancel(true) sets the interrupt flag on the worker thread and nothing more. A task that never checks Thread.interrupted() and never calls a blocking method keeps running to completion. Java cannot kill a thread safely, so cooperation is the only mechanism there is.
Failures arrive wrapped. If the task throws, get() throws ExecutionException, and the exception you actually wrote is in getCause(). This surprises people, because a stack trace you print without unwrapping points at the waiting thread, not at the line that broke. Since Java 19 there is also state(), returning RUNNING, SUCCESS, FAILED, or CANCELLED, so you can inspect the outcome without a try/catch around get().
Order matters when you fan out. Submit every task first, collect the futures, and only then loop over them calling get(). Calling get() inside the submission loop makes the code sequential again with extra machinery: each iteration waits for its own task before the next one is even submitted.
The real limitation is that a Future gives you no way to say "when this finishes, do that". You can only block. Building a pipeline out of plain futures means a thread parked on get() for every step, which wastes exactly the threads you were trying to conserve. That gap is why CompletableFuture was added in Java 8, and why Java 21's StructuredTaskScope exists for the fan-out-and-join case.
Future is still the right tool when you submit a handful of independent tasks and genuinely need all their results before continuing: pricing three vendors before rendering a page, or validating an upload against two services. With virtual threads, blocking on get() is cheap again, so the old advice to avoid it applies mainly to platform threads.
The cost of blocking is a thread doing nothing. One parked platform thread is about 1 MB of stack and a slot in your pool that no other request can use.
Code Examples
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;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class FutureBasics {
public static void main(String[] args) throws InterruptedException {
try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
Future<Integer> answer = pool.submit(() -> 6 * 7);
// Declared as a Callable so the compiler knows the element type
// even though this body only throws.
Callable<Integer> failing = () -> {
throw new IllegalStateException("pricing service down");
};
Future<Integer> broken = pool.submit(failing);
try {
// Bounded wait: never call the no-argument get() on a remote call.
System.out.println(answer.get(2, TimeUnit.SECONDS)); // 42
} catch (ExecutionException e) {
System.out.println("task threw: " + e.getCause());
} catch (TimeoutException e) {
answer.cancel(true); // interrupt the worker, if it cooperates
}
try {
broken.get();
} catch (ExecutionException e) {
// The exception the task threw is one level down, in the cause.
System.out.println("failed because: " + e.getCause().getMessage());
}
System.out.println(answer.state()); // SUCCESS (Java 19+)
System.out.println(broken.state()); // FAILED
}
}
}import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicBoolean;
public class Cancellable {
public static void main(String[] args) throws Exception {
AtomicBoolean finished = new AtomicBoolean(false);
try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
Future<?> job = pool.submit(() -> {
// A long loop must check the interrupt flag, or cancel(true) does nothing.
while (!Thread.currentThread().isInterrupted()) {
// pretend to process one record of a large export
}
finished.set(true);
});
Thread.sleep(100);
job.cancel(true); // requests interruption
System.out.println(job.isCancelled()); // true
}
System.out.println("loop exited: " + finished.get()); // true
}
}Common Gotchas
The exception you wrote is not the exception you catch
`get()` throws `ExecutionException`. Log or rethrow `e.getCause()`, otherwise your stack trace points at the waiting thread and hides the real failure.
Swallowing InterruptedException breaks cancellation
`get()` throws it when the waiting thread is interrupted. Catching it and doing nothing discards the signal. Either propagate it or call `Thread.currentThread().interrupt()` to restore the flag.
`cancel(true)` is a request, not a kill
a running task that ignores interruption runs to the end while your code believes it stopped. Check `Thread.currentThread().isInterrupted()` inside long loops.
Calling `get()` in the submission loop removes the parallelism
the tasks run one at a time, in order, with pool overhead on top. Submit all of them, then wait.