Java Future Interface
The Java Future interface represents the result of a task that is running, or will run, on another thread. When you submit a task to an ExecutorService, you get a Future back immediately, and you use it later to wait for the result, check progress, handle errors or cancel the task.
Future lives in the java.util.concurrent package. This lesson covers every method of the interface, from the classic get() and cancel() to the newer state(), resultNow() and exceptionNow() methods added in Java 19.
What Is the Java Future Interface?
Think of a Future as a receipt from a dry cleaner. You hand over your clothes (the task), get a receipt (the Future), and go about your day. Later you return with the receipt to pick up the result, or to ask whether it is ready yet.
A Future<V> is generic: V is the type of the result. A task that returns an Integer gives you a Future<Integer>.
| Method | What it does |
|---|---|
V get() | Waits until the task finishes, then returns its result |
V get(long timeout, TimeUnit unit) | Waits at most the given time, then throws TimeoutException |
boolean isDone() | true when the task finished, failed or was cancelled |
boolean cancel(boolean mayInterruptIfRunning) | Tries to stop the task |
boolean isCancelled() | true if the task was cancelled before it completed |
Future.State state() (Java 19+) | RUNNING, SUCCESS, FAILED or CANCELLED |
V resultNow() (Java 19+) | The result of a successful task, without waiting |
Throwable exceptionNow() (Java 19+) | The exception of a failed task, without waiting |
Note:
Futureis only a handle to the result. The task itself is usually a Callable or aRunnable, and an ExecutorService runs it.
Getting a Result with Future.get()
ExecutorService.submit() starts a task and returns a Future straight away. Calling get() on that Future returns the result once it is available.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureBasics {
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
// submit() returns at once with a Future for the coming result
Future<Integer> futureSum = executor.submit(() -> {
int sum = 0;
for (int number = 1; number <= 100; number++) {
sum += number;
}
return sum;
});
System.out.println("Task submitted, isDone = " + futureSum.isDone());
Integer sum = futureSum.get(); // waits for the task if needed
System.out.println("Sum of 1..100 = " + sum);
System.out.println("isDone = " + futureSum.isDone());
}
}
}
Output (the first isDone value can also be true if the task is very fast):
Task submitted, isDone = false
Sum of 1..100 = 5050
isDone = true
How it works:
- The lambda returns a value, so Java treats it as a
Callable<Integer>, andsubmit()returns aFuture<Integer>. - Right after
submit(), the task may still be running, soisDone()is usuallyfalse. get()returns5050once the task has finished. After that,isDone()is alwaystrue.- The try-with-resources block closes the executor (Java 19+), which waits for running tasks to end.
Future.get() Blocks the Calling Thread
get() is a blocking call: the thread that calls it stops and waits until the result is ready. The useful pattern is to submit work first, do something else, and call get() only when you actually need the value.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureBlocking {
public static void main(String[] args) throws Exception {
long start = System.currentTimeMillis();
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<String> report = executor.submit(() -> {
Thread.sleep(1000); // a slow report: 1 second
return "Monthly report";
});
// Main does its own work while the report is being built
Thread.sleep(600);
System.out.println("Main finished its own work after "
+ roundToHundred(System.currentTimeMillis() - start) + " ms");
String result = report.get(); // waits only for the remaining time
System.out.println("Got '" + result + "' after "
+ roundToHundred(System.currentTimeMillis() - start) + " ms");
}
}
static long roundToHundred(long millis) {
return Math.round(millis / 100.0) * 100;
}
}
Output:
Main finished its own work after 600 ms
Got 'Monthly report' after 1000 ms
How it works:
- The report task and main's own 600 ms of work run at the same time.
- When main calls
get(), the report still needs about 400 ms, soget()waits only for that remaining time. - The whole program takes about 1000 ms instead of 1600 ms, because the two waits overlap.
Note: Calling
get()right aftersubmit()throws away the benefit of running the task on another thread. Submit early, callget()late.
Checking Progress with isDone()
isDone() never blocks. You can use it to check whether a result is ready and do something else, such as updating a progress message, while you wait.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureIsDone {
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<Long> download = executor.submit(() -> {
Thread.sleep(700); // simulated download
return 4_096L; // bytes downloaded
});
int check = 1;
while (!download.isDone()) {
System.out.println("Check " + check++ + ": download still running...");
Thread.sleep(200);
}
System.out.println("Download finished: " + download.get() + " bytes");
}
}
}
Output from one run:
Check 1: download still running...
Check 2: download still running...
Check 3: download still running...
Check 4: download still running...
Download finished: 4096 bytes
How it works:
- The loop checks
isDone()every 200 ms. Each check returns instantly. - After about 700 ms the task completes,
isDone()becomestrue, and the loop ends. - At that point
get()returns immediately, because the result is already there.
Java Future get() with a Timeout
A plain get() waits forever if the task hangs. The overloaded get(timeout, unit) waits for at most the given time. If the result is not ready, it throws a TimeoutException, but the task keeps running, so you can decide to wait again or give up.
Syntax
V result = future.get(long timeout, TimeUnit unit); // throws TimeoutException
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 FutureTimeout {
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<String> translation = executor.submit(() -> {
Thread.sleep(800); // a translation service that takes 0.8 s
return "Vanakkam";
});
try {
System.out.println(translation.get(300, TimeUnit.MILLISECONDS));
} catch (TimeoutException e) {
System.out.println("Not ready after 300 ms, showing a spinner...");
}
// The task is still running, so we can wait again
String result = translation.get(2, TimeUnit.SECONDS);
System.out.println("Translation: " + result);
}
}
}
Output:
Not ready after 300 ms, showing a spinner...
Translation: Vanakkam
How it works:
- The first
get()gives up after 300 ms and throwsTimeoutException. - A timeout does not cancel the task. The translation keeps running on the pool thread.
- The second
get()allows up to 2 seconds, which is enough, so it returns the result.
Cancelling a Task with Future.cancel()
cancel(mayInterruptIfRunning) tries to stop a task. What happens depends on the task's state and on the argument:
| Situation | cancel(false) | cancel(true) |
|---|---|---|
| Task has not started yet | Task will never run | Task will never run |
| Task is running | Task continues to the end; its result is discarded | The worker thread is interrupted |
| Task already finished | Returns false, nothing changes | Returns false, nothing changes |
After a successful cancel, isCancelled() and isDone() both return true, and get() throws a CancellationException.
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureCancel {
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<String> backup = executor.submit(() -> {
for (int part = 1; part <= 100; part++) {
try {
Thread.sleep(50); // copy one part of the backup
} catch (InterruptedException e) {
System.out.println("Worker: interrupted at part " + part + ", cleaning up");
return "partial backup";
}
}
return "full backup";
});
Thread.sleep(230); // let the backup run for a while
boolean cancelled = backup.cancel(true); // interrupt the worker
Thread.sleep(100); // give the worker time to print
System.out.println("cancel returned : " + cancelled);
System.out.println("isCancelled : " + backup.isCancelled());
System.out.println("isDone : " + backup.isDone());
try {
backup.get();
} catch (CancellationException e) {
System.out.println("get() threw : " + e.getClass().getSimpleName());
}
}
}
}
Output:
Worker: interrupted at part 5, cleaning up
cancel returned : true
isCancelled : true
isDone : true
get() threw : CancellationException
How it works:
cancel(true)interrupts the worker thread, so theThread.sleep(50)inside the loop throwsInterruptedException.- The task catches it, prints a message and returns early. Its return value is thrown away because the
Futureis already cancelled. get()on a cancelledFuturethrowsCancellationException, an unchecked exception.
Note: Interruption is a request, not a command. A task that never sleeps, waits or checks
Thread.currentThread().isInterrupted()will keep running even aftercancel(true).
Handling Exceptions from a Future
If the task throws an exception, the Future stores it. get() then throws an ExecutionException that wraps the original exception, which you read with getCause(). Since Java 19, exceptionNow() returns the original exception directly for a failed task.
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureException {
public static void main(String[] args) throws InterruptedException {
int totalMarks = 450;
int subjects = 0; // a bug: no subjects recorded
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Future<Integer> average = executor.submit(() -> totalMarks / subjects);
try {
System.out.println("Average: " + average.get());
} catch (ExecutionException e) {
System.out.println("Task failed: " + e.getCause());
}
System.out.println("state = " + average.state());
System.out.println("exceptionNow = " + average.exceptionNow());
}
}
}
Output:
Task failed: java.lang.ArithmeticException: / by zero
state = FAILED
exceptionNow = java.lang.ArithmeticException: / by zero
How it works:
- The division by zero happens on the pool thread, not in
main, somaindoes not crash. get()throwsExecutionException;getCause()returns theArithmeticExceptionthrown by the task.state()reportsFAILED, andexceptionNow()returns the same exception without any wrapping.
Future with a Runnable: Future<?>
You can also submit a Runnable, which returns no value. submit() then returns a Future<?>, and get() returns null when the task completes. This is still useful for waiting, cancelling and catching exceptions.
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureRunnable {
public static void main(String[] args) throws Exception {
try (ExecutorService executor = Executors.newSingleThreadExecutor()) {
Runnable sendEmail = () -> System.out.println("Email sent on " + Thread.currentThread().getName());
Future<?> emailTask = executor.submit(sendEmail);
Object result = emailTask.get(); // waits for the Runnable to finish
System.out.println("get() returned: " + result);
// submit(Runnable, result) lets you choose the value get() returns
Future<String> withResult = executor.submit(sendEmail, "DELIVERED");
System.out.println("get() returned: " + withResult.get());
}
}
}
Output:
Email sent on pool-1-thread-1
get() returned: null
Email sent on pool-1-thread-1
get() returned: DELIVERED
How it works:
submit(Runnable)returnsFuture<?>.get()only tells you that the task is finished, so it returnsnull.submit(Runnable, result)returns aFuture<T>whoseget()returns the value you passed in once the task is done.
Reading Future.state(), resultNow() and exceptionNow()
Java 19 added three methods that inspect a Future without blocking. state() returns a Future.State enum, which works well with a switch. resultNow() and exceptionNow() throw IllegalStateException if the Future is not in the matching state.
state() | Meaning | Safe method to call |
|---|---|---|
RUNNING | Not finished yet | none (wait or check later) |
SUCCESS | Completed normally | resultNow() |
FAILED | Threw an exception | exceptionNow() |
CANCELLED | Cancelled | none |
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class FutureStates {
public static void main(String[] args) throws InterruptedException {
try (ExecutorService executor = Executors.newFixedThreadPool(4)) {
Future<String> quick = executor.submit(() -> "done quickly");
Future<String> broken = executor.submit(() -> {
throw new IllegalArgumentException("bad input");
});
Future<String> slow = executor.submit(() -> {
Thread.sleep(2000);
return "done slowly";
});
Future<String> stopped = executor.submit(() -> {
Thread.sleep(2000);
return "never seen";
});
stopped.cancel(true);
Thread.sleep(300); // give the quick tasks time to finish
List<Future<String>> futures = List.of(quick, broken, slow, stopped);
for (Future<String> future : futures) {
String description = switch (future.state()) {
case SUCCESS -> "SUCCESS -> " + future.resultNow();
case FAILED -> "FAILED -> " + future.exceptionNow().getMessage();
case CANCELLED -> "CANCELLED -> no result";
case RUNNING -> "RUNNING -> still working";
};
System.out.println(description);
}
slow.cancel(true); // do not keep the executor waiting
}
}
}
Output:
SUCCESS -> done quickly
FAILED -> bad input
RUNNING -> still working
CANCELLED -> no result
How it works:
- Four tasks end up in the four possible states: one succeeds, one throws, one is still sleeping and one was cancelled.
- The
switchcovers everyFuture.Stateconstant, so nodefaultbranch is needed. resultNow()andexceptionNow()are called only in the branch where they are valid, so they never throw.- The last line cancels the slow task, so closing the executor does not wait two seconds for it.
Real-World Example: Loading a Dashboard with Futures
A user dashboard needs three pieces of data from three services: the profile, recent orders and product recommendations. The page must render within 500 ms. Required data must arrive; optional data falls back to a default if its service is slow or broken.
import java.util.List;
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 DashboardLoader {
record Dashboard(String profile, List<String> orders, List<String> recommendations) { }
// Simulated remote calls with different speeds and behaviours
static String loadProfile(int userId) throws InterruptedException {
Thread.sleep(120);
return "Priya (user " + userId + ")";
}
static List<String> loadOrders(int userId) throws InterruptedException {
Thread.sleep(250);
return List.of("#1001 Java book", "#1002 USB-C cable");
}
static List<String> loadRecommendations(int userId) throws InterruptedException {
Thread.sleep(2000); // the recommendation service is overloaded today
return List.of("Mechanical keyboard");
}
// Waits until the shared deadline; returns the fallback on timeout or failure
static <T> T getOrDefault(Future<T> future, long deadline, T fallback, String name)
throws InterruptedException {
long remaining = Math.max(0, deadline - System.currentTimeMillis());
try {
return future.get(remaining, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
future.cancel(true); // stop work nobody will use
System.out.println("[warn] " + name + " timed out, using fallback");
} catch (ExecutionException e) {
System.out.println("[warn] " + name + " failed: " + e.getCause().getMessage());
}
return fallback;
}
public static void main(String[] args) throws Exception {
int userId = 42;
long start = System.currentTimeMillis();
long deadline = start + 500; // one deadline for the whole page
try (ExecutorService executor = Executors.newFixedThreadPool(3)) {
// 1. Start all three calls at once
Future<String> profileFuture = executor.submit(() -> loadProfile(userId));
Future<List<String>> ordersFuture = executor.submit(() -> loadOrders(userId));
Future<List<String>> recsFuture = executor.submit(() -> loadRecommendations(userId));
// 2. Collect the results, each limited by the same deadline
String profile = profileFuture.get(); // required: no fallback
List<String> orders = getOrDefault(ordersFuture, deadline, List.of(), "orders");
List<String> recs = getOrDefault(recsFuture, deadline, List.of("Top sellers"), "recommendations");
Dashboard dashboard = new Dashboard(profile, orders, recs);
long elapsed = Math.round((System.currentTimeMillis() - start) / 100.0) * 100;
System.out.println("Profile : " + dashboard.profile());
System.out.println("Orders : " + dashboard.orders());
System.out.println("Recommendations: " + dashboard.recommendations());
System.out.println("Rendered in about " + elapsed + " ms");
}
}
}
Output:
[warn] recommendations timed out, using fallback
Profile : Priya (user 42)
Orders : [#1001 Java book, #1002 USB-C cable]
Recommendations: [Top sellers]
Rendered in about 500 ms
How it works:
- Parallel calls. All three loads are submitted before any
get()call, so they run at the same time on a pool of three threads. - One shared deadline.
getOrDefault()computes how much of the 500 ms budget is left and passes only that toget(timeout, unit). The page can never take much longer than 500 ms, however many services it calls. - Fallbacks. The recommendation service needs 2 seconds, so its
get()times out. The helper cancels the task and returns the default list[Top sellers]. - Errors stay contained. An
ExecutionExceptionfrom an optional service is logged and replaced by the fallback instead of breaking the whole page. - Cancelling unused work.
cancel(true)interrupts the slow call, so the executor can close without waiting the full 2 seconds.
A Future can only be waited on; it cannot run a follow-up step when the result arrives. The next lesson, Java CompletableFuture, adds that ability, letting you chain and combine asynchronous results without blocking. For running the tasks themselves, see Java Thread Pools.