Skip to lesson

Why CompletableFuture?

A CompletableFuture is a future you can attach next steps to: "when the fare arrives, add GST, then show it". The calling thread does not have to stop and wait for the result.

Future.get() blocks the caller

CompletableFuture represents a result that will be ready later and lets you chain the next steps and handle errors without blocking a thread.

Future.get() returns a task's result, but if the task is still running it blocks: the calling thread stops and waits until the result is ready. While it waits, that thread can do nothing else.

Example 1 · Future.get() keeps main waiting

FutureGetDemo.javaJava
import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class FutureGetDemo {    static int fetchFare(String train) {        sleep(200);                     // pretend this is a slow railway server        return 1450;    }
    static void sleep(long ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) throws Exception {        ExecutorService pool = Executors.newSingleThreadExecutor();        Future<Integer> fare = pool.submit(() -> fetchFare("12951 Rajdhani"));        System.out.println("Fare request sent");
        System.out.println("main: calling get()...");        long start = System.currentTimeMillis();        int rupees = fare.get();                    // main is stuck here        long waited = System.currentTimeMillis() - start;
        System.out.println("main: got Rs " + rupees);        System.out.println("main was blocked for at least 150 ms: " + (waited >= 150));        pool.shutdown();    }}
Output
Fare request sent
main: calling get()...
main: got Rs 1450
main was blocked for at least 150 ms: true

What this code does

  • fare.get() stops main until the pool thread returns 1450. For about 200 ms, main cannot show anything else to the user.
  • The only other choice with a plain Future is to ask isDone() again and again, which wastes the thread in a different way.

A plain Future has only a few methods: get, isDone and cancel. To use the result you must either block with get() or keep asking isDone() in a loop. There is no way to say "run this when the result is ready". This gets worse with more tasks. To add a train fare and a hotel price from two futures, you block on the first, then block on the second, then add. Each new step means one more blocked thread.

Blocking is fine in a small program. It hurts in a server, where every blocked thread is a thread that cannot serve another user.

Saying what to do when the result arrives

A callback is a piece of code you hand over now, to be run later when the result is ready. CompletableFuture lets you attach callbacks such as thenAccept(...) instead of waiting with get().

Example 2 · A callback runs when the fare arrives

CallbackDemo.javaJava
import java.util.concurrent.CompletableFuture;
public class CallbackDemo {    static int fetchFare(String train) {        sleep(200);                     // pretend this is a slow railway server        return 1450;    }
    static void sleep(long ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) {        CompletableFuture<Void> done = CompletableFuture                .supplyAsync(() -> fetchFare("12951 Rajdhani"))                .thenAccept(rupees -> System.out.println("Callback: fare is Rs " + rupees));
        System.out.println("main: request sent, main is free");        System.out.println("main: showing the seat map meanwhile");
        done.join();        // only so the program does not end too early        System.out.println("main: finished");    }}
Output
main: request sent, main is free
main: showing the seat map meanwhile
Callback: fare is Rs 1450
main: finished

What this code does

  • supplyAsync starts fetchFare on a background thread, and thenAccept registers what to do with the result. Both calls return at once, so main prints its two lines straight away.
  • About 200 ms later the fare arrives and the callback prints it. main never called get() to wait for the fare itself.

The calling thread registers the step and moves on. When the background task finishes, the step runs with the result. Nobody stands waiting in between. The join() at the end of main is there only so the program does not end before the callback runs. The next lesson, supplyAsync and runAsync, explains why.

A pickup token as an analogy

A pickup token is a good picture of a future: you order online, get token 42 and carry on with your day, and the parcel is packed later. This is a simplified picture, but it matches the code closely.

Example 3 · A pickup token completed by the warehouse

PickupTokenDemo.javaJava
import java.util.concurrent.CompletableFuture;
public class PickupTokenDemo {    static void sleep(long ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) throws InterruptedException {        CompletableFuture<String> token42 = new CompletableFuture<>();        System.out.println("Token 42 given. Done yet? " + token42.isDone());
        token42.thenAccept(item -> System.out.println("Display: token 42, your " + item + " is ready"));        System.out.println("Customer carries on with other work");
        Thread warehouse = new Thread(() -> {            sleep(100);                       // packing            token42.complete("Laptop");        }, "warehouse");        warehouse.start();        warehouse.join();
        boolean again = token42.complete("Mouse");        System.out.println("Second complete accepted? " + again);        System.out.println("Done yet? " + token42.isDone() + ", item = " + token42.join());    }}
Output
Token 42 given. Done yet? false
Customer carries on with other work
Display: token 42, your Laptop is ready
Second complete accepted? false
Done yet? true, item = Laptop

What this code does

  • new CompletableFuture<>() is an empty token. The callback is attached first, and it runs only when the warehouse thread calls complete("Laptop").
  • The second complete("Mouse") returns false and changes nothing: a future is completed once, by whichever thread gets there first.

With a plain Future, you wait at the collection desk holding the token until the parcel comes: that is get(). With a CompletableFuture, you tell the desk "when 42 is ready, send it to my address": that is a callback. The warehouse marks the order done with complete(item), which is where the name Completable comes from. Any thread holding the future can complete it, but only once. A second complete call is ignored and returns false.

Pipelines of steps, like streams

A pipeline is a chain of steps where each step takes the previous step's result. CompletableFuture builds pipelines the way streams do: supplyAsync starts it, thenApply transforms the value, thenAccept uses the final value.

Example 4 · A result pipeline: fetch, total, percentage, grade

ResultPipelineDemo.javaJava
import java.util.List;import java.util.concurrent.CompletableFuture;
public class ResultPipelineDemo {    static List<Integer> fetchMarks(String roll) {        sleep(150);                     // pretend this is the exam result server        return List.of(78, 85, 91, 66, 88);    }
    static void sleep(long ms) {        try {            Thread.sleep(ms);        } catch (InterruptedException e) {            Thread.currentThread().interrupt();        }    }
    public static void main(String[] args) {        CompletableFuture<String> result = CompletableFuture                .supplyAsync(() -> fetchMarks("21CS042"))                    // step 1: fetch                .thenApply(marks -> marks.stream().mapToInt(Integer::intValue).sum())                .thenApply(total -> total * 100.0 / 500)                .thenApply(pct -> (pct >= 75 ? "Distinction" : "Pass") + " (" + pct + "%)"); // step 4
        System.out.println("Pipeline built, main is free");        System.out.println("Result: " + result.join());    }}
Output
Pipeline built, main is free
Result: Distinction (81.6%)

What this code does

  • Each thenApply takes the previous value and returns a new one: a List<Integer>, then the total 408, then 81.6, then the grade text.
  • The whole chain is built in a moment and main prints its line first. The four steps run later, in order, once the marks arrive.
  • Future: get, isDone, cancel. You wait or you keep checking.
  • CompletableFuture: all of that, plus complete and steps such as thenApply, thenAccept, thenCombine.
  • Stream: a pipeline over many values, run now. CompletableFuture: a pipeline over one value, run when it arrives.

Each thenApply returns a new CompletableFuture, so the calls chain. Building the chain takes almost no time; the steps run later, one after another, as each result arrives. CompletableFuture (Java 8) implements Future, so get() still works, and CompletionStage, the interface that holds the then... methods.

Order of execution

Run a CompletableFuture pipeline

The marks pipeline from Example 4. Put the steps in the order they happen.

Next step

Check your understanding

10 quick questions