Java Future Interface

Su Suriya Ravichandran Updated 18 Nov 2026
13 min read ·Lesson 196 of 306

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>.

MethodWhat 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: Future is only a handle to the result. The task itself is usually a Callable or a Runnable, 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>, and submit() returns a Future<Integer>.
  • Right after submit(), the task may still be running, so isDone() is usually false.
  • get() returns 5050 once the task has finished. After that, isDone() is always true.
  • 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, so get() 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 after submit() throws away the benefit of running the task on another thread. Submit early, call get() 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() becomes true, 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 throws TimeoutException.
  • 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:

Situationcancel(false)cancel(true)
Task has not started yetTask will never runTask will never run
Task is runningTask continues to the end; its result is discardedThe worker thread is interrupted
Task already finishedReturns false, nothing changesReturns 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 the Thread.sleep(50) inside the loop throws InterruptedException.
  • The task catches it, prints a message and returns early. Its return value is thrown away because the Future is already cancelled.
  • get() on a cancelled Future throws CancellationException, 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 after cancel(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, so main does not crash.
  • get() throws ExecutionException; getCause() returns the ArithmeticException thrown by the task.
  • state() reports FAILED, and exceptionNow() 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) returns Future<?>. get() only tells you that the task is finished, so it returns null.
  • submit(Runnable, result) returns a Future<T> whose get() 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()MeaningSafe method to call
RUNNINGNot finished yetnone (wait or check later)
SUCCESSCompleted normallyresultNow()
FAILEDThrew an exceptionexceptionNow()
CANCELLEDCancellednone
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 switch covers every Future.State constant, so no default branch is needed.
  • resultNow() and exceptionNow() 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:

  1. Parallel calls. All three loads are submitted before any get() call, so they run at the same time on a pool of three threads.
  2. One shared deadline. getOrDefault() computes how much of the 500 ms budget is left and passes only that to get(timeout, unit). The page can never take much longer than 500 ms, however many services it calls.
  3. Fallbacks. The recommendation service needs 2 seconds, so its get() times out. The helper cancels the task and returns the default list [Top sellers].
  4. Errors stay contained. An ExecutionException from an optional service is logged and replaced by the fallback instead of breaking the whole page.
  5. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Future Interface and get answers drawn from it.

Signed-in readers only.