FutureTask Class in Java: A Cancellable, Run-Once Task
FutureTask is the class that executors use behind the scenes for every task you submit. It wraps a Callable or Runnable, runs it at most once, and stores the outcome so that any thread can read it through the Future API.
This tutorial covers its constructors, its run-once and cancellation rules, and its protected hooks, especially the done() completion callback.
1. What Is FutureTask?
FutureTask<V> is a class in java.util.concurrent, added in Java 5, that implements RunnableFuture<V>. Because it is a Runnable, you can hand it to a Thread or an Executor; because it is a Future, you can wait for and cancel it.
ExecutorService.submit() returns a FutureTask by default, through the newTaskFor() hook of AbstractExecutorService.
2. FutureTask Hierarchy
Swipe sideways to see the whole diagram.
Runnable(java.lang interface): Lets threads and executors run the task.Future(interface): Lets callers wait for the result, check its state and cancel.RunnableFuture(interface): Joins the two; its run() sets the Future's result.
3. Constructor Details
| Constructor | Description |
|---|---|
FutureTask(Callable<V> callable) | Runs the callable; get() returns its result. |
FutureTask(Runnable runnable, V result) | Runs the runnable; get() returns the given result. Pass null if you do not need one. |
4. Method Details
| Method | Description |
|---|---|
run() | Runs the computation once; does nothing if the task has already completed or been cancelled. |
get(), get(timeout, unit) | Wait for the result, as defined by Future. |
cancel(mayInterrupt) | Cancels the task if it has not completed. |
state(), resultNow(), exceptionNow() | Java 19+ inspection methods. |
done() | Protected; called once when the task completes or is cancelled. Does nothing by default. |
set(V), setException(Throwable) | Protected; used by run() to record the outcome. |
runAndReset() | Protected; runs without storing a result, so the task can run again (used for periodic tasks). |
5. Example: Run Once, Even If Started Twice
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;
public class ExchangeRateTask {
static final AtomicInteger apiCalls = new AtomicInteger();
public static void main(String[] args) throws InterruptedException, ExecutionException {
FutureTask<Double> eurToUsd = new FutureTask<>(() -> {
apiCalls.incrementAndGet(); // count real calls to the rate API
Thread.sleep(100);
return 1.0842;
}) {
@Override
protected void done() { // completion callback
System.out.println("done() called, cancelled = " + isCancelled());
}
};
Thread first = new Thread(eurToUsd);
Thread second = new Thread(eurToUsd); // the same task handed to a second thread
first.start();
second.start();
first.join();
second.join();
System.out.println("Rate: " + eurToUsd.get());
System.out.println("API calls made: " + apiCalls.get());
System.out.println("state(): " + eurToUsd.state());
}
}
done() called, cancelled = false Rate: 1.0842 API calls made: 1 state(): SUCCESS
How the code works
- The FutureTask wraps a Callable that calls a (simulated) exchange-rate API and counts how often it runs.
- An anonymous subclass overrides
done(), which runs once when the task completes. - The same task is given to two threads. Only one of them performs the computation; the other finds the task already running or finished and returns immediately.
- So the API is called exactly once, and both threads, and the main thread, see the same rate.
6. Example: Cancelling Before It Runs
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CancelledBeforeRun {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// FutureTask(Runnable, result): the Runnable does the work, get() returns the fixed result
FutureTask<String> emailBlast = new FutureTask<>(
() -> System.out.println("Sending 10,000 marketing emails..."), "sent");
boolean cancelled = emailBlast.cancel(false); // the campaign is withdrawn before it starts
System.out.println("cancel() returned: " + cancelled);
emailBlast.run(); // has no effect: the task is already done
System.out.println("isDone: " + emailBlast.isDone() + ", state: " + emailBlast.state());
try {
emailBlast.get();
} catch (CancellationException e) {
System.out.println("get() threw CancellationException");
}
}
}
cancel() returned: true isDone: true, state: CANCELLED get() threw CancellationException
How the code works
- The
FutureTask(Runnable, "sent")constructor wraps a Runnable and a fixed result. cancel(false)succeeds because the task has not started.- Calling
run()afterwards does nothing, so no emails are sent. get()on a cancelled task throwsCancellationException, andstate()reportsCANCELLED.
7. Common Mistakes and Best Practices
- Expecting reuse. A completed FutureTask never runs again; create a new one for each computation.
- Heavy work in
done(). It runs on the thread that completed or cancelled the task; keep it short and never block in it. - Exceptions inside
done(). They are not reported through the Future, so handle them inside the method. - Using it for pipelines. For chained asynchronous steps, prefer CompletableFuture.
- Good use case. Memoising an expensive result: store one FutureTask in a map so concurrent callers share a single computation.
8. Summary
FutureTaskimplementsRunnableFuture: it can be run like a Runnable and read like a Future.- It computes its result at most once, even if several threads call run().
- A task cancelled before it starts never runs, and
get()throwsCancellationException. - Override the protected
done()hook for completion callbacks.
Related Tutorials
9. References
Frequently Asked Questions (FAQ)
Q1. Can a FutureTask be run more than once?
No. Once it has completed or been cancelled, further calls to run() have no effect. The protected runAndReset() method exists for subclasses that need to run a computation repeatedly, as scheduled periodic tasks do.
Q2. When is done() called?
Once, when the task transitions to the done state, whether it completed normally, threw an exception or was cancelled. Inside done() you can call isCancelled() to see which.
Q3. What is the difference between FutureTask and CompletableFuture?
A FutureTask completes by running its wrapped task and offers only blocking access to the result. A CompletableFuture can be completed explicitly from any thread and supports non-blocking callbacks such as thenApply().
Q4. Does ExecutorService.submit() return a FutureTask?
With executors built on AbstractExecutorService, such as ThreadPoolExecutor, yes: the default newTaskFor() creates a FutureTask. The declared return type is just Future, so do not depend on the concrete class.
Q5. Can I pass a FutureTask to a Thread?
Yes. FutureTask implements Runnable, so new Thread(futureTask).start() runs it, and you can then call futureTask.get() for the result.