00:00

FutureTask Class in Java: A Cancellable, Run-Once Task

Last updated:

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

FutureTask class hierarchyFutureTask implements RunnableFuture, which extends java.lang.Runnable and Future.«interface» · java.langRunnablerun()«interface»Future<V>get(), cancel(…)«interface»RunnableFuture<V>run()«class»FutureTask<V>this pageFutureTask(Callable<V>)FutureTask(Runnable, V)run(), get(), cancel(…)done() «protected»set(V), setException(…) «protected»extendsimplementsinterfaceclassjava.lang type

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

ConstructorDescription
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

MethodDescription
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

ExchangeRateTask.java
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());
    }
}
Output
done() called, cancelled = false
Rate: 1.0842
API calls made: 1
state(): SUCCESS

How the code works

  1. The FutureTask wraps a Callable that calls a (simulated) exchange-rate API and counts how often it runs.
  2. An anonymous subclass overrides done(), which runs once when the task completes.
  3. 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.
  4. So the API is called exactly once, and both threads, and the main thread, see the same rate.

6. Example: Cancelling Before It Runs

CancelledBeforeRun.java
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");
        }
    }
}
Output
cancel() returned: true
isDone: true, state: CANCELLED
get() threw CancellationException

How the code works

  1. The FutureTask(Runnable, "sent") constructor wraps a Runnable and a fixed result.
  2. cancel(false) succeeds because the task has not started.
  3. Calling run() afterwards does nothing, so no emails are sent.
  4. get() on a cancelled task throws CancellationException, and state() reports CANCELLED.

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

  • FutureTask implements RunnableFuture: 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() throws CancellationException.
  • Override the protected done() hook for completion callbacks.

Related Tutorials

9. References