Future, Callable & CompletableFuture
Callable, Future, CompletableFuture async pipelines, thenApply/thenCompose/allOf
- Use Callable to return values from async tasks
- Build non-blocking pipelines with CompletableFuture
- Combine multiple futures with allOf, anyOf, thenCombine
Complete Study Guide Chapter: Asynchronous Programming in Java
ThreadPoolExecutor, Runnable, and basic Java threading. Where those concepts are referenced, enough context is provided to keep this guide self-contained.Table of Contents
- The Problem: Tracking Async Tasks
- Future — The Interface
- Callable — Returning Values from Threads
- Three Flavors of
submit() - Internal Working: FutureTask
- CompletableFuture — Advanced Async
- CompletableFuture Methods In Depth
- Interview Notes
- Common Mistakes
- Best Practices
- Practice Questions
- Summary
1. The Problem: Tracking Async Tasks
Overview
When you submit a task to a ThreadPoolExecutor, the calling thread (e.g., the main thread) does not wait for the submitted task to complete. A worker thread from the pool picks up the task and runs it independently.
This is the essence of asynchronous execution: the caller continues processing while the task runs elsewhere.
Why This Creates a Problem
Consider this scenario:
1Main Thread Worker Thread (T1)2───────────── ──────────────────3submit task ──────► [running task...]4continue... [still running...]5 [done]After submitting the task, the main thread has no reference to that task. It cannot know:
- Has the task completed?
- Did the task fail with an exception?
- What result did the task produce?
1// Without Future — no way to track the task2ExecutorService pool = Executors.newFixedThreadPool(1);3pool.submit(() -> {4 System.out.println("Task running...");5 Thread.sleep(2000);6});7// Main continues here — has zero knowledge of task statusFuture reference, the caller has no mechanism to observe task state, retrieve results, or handle exceptions.This is precisely the problem that Future was designed to solve.
2. Future The Interface
Definition
Future is a Java interface (in java.util.concurrent) that represents the result of an asynchronous computation. It provides a handle through which the caller can:
- Check if the computation is complete
- Retrieve the result once complete
- Cancel the task if it is still pending
- Detect exceptions that occurred during execution
Real-world Analogy
Think of ordering food at a restaurant.
- You place an order (submit a task) and get a receipt/token (the
Futureobject). - You don't stand in the kitchen watching — you continue sitting, chatting (main thread continues).
- When you want to check, you look at the token: "Is my order ready?"
- You can also choose to wait at the counter until the food arrives (
future.get()). - You could even cancel the order before it is prepared (
future.cancel()).
Interface Declaration
1public interface Future<V> {2 boolean cancel(boolean mayInterruptIfRunning);3 boolean isCancelled();4 boolean isDone();5 V get() throws InterruptedException, ExecutionException;6 V get(long timeout, TimeUnit unit)7 throws InterruptedException, ExecutionException, TimeoutException;8}Methods of Future Detailed
Method 1: `cancel(boolean mayInterruptIfRunning)`
1boolean result = futureObj.cancel(true);| Parameter | Description |
|---|---|
true | Attempt to interrupt the thread if it is running |
false | Cancel only if the task has not yet started |
Return values:
true— Task was successfully canceled (was pending or was interrupted)false— Task cannot be canceled (already completed, already canceled, or could not be interrupted)
cancel() always returns false. There is nothing to cancel.Method 2: `isCancelled()`
1boolean canceled = futureObj.isCancelled();Returns true if the task was canceled before it completed normally.
- Use this to confirm that a
cancel()call actually took effect. - Distinct from
cancel()—isCancelled()just queries the state; it does not change it.
Method 3: `isDone()`
1boolean done = futureObj.isDone();Returns true if the task finished, regardless of how it finished:
- Normal completion ✅
- Exception thrown ✅
- Task was canceled ✅
Returns false only if the task is still in progress.
isDone() is a non-blocking check. It returns immediately without waiting for the task.Method 4: `get()`
1V result = futureObj.get();Blocks the calling thread until the async task completes. Once it completes, retrieves and returns the result.
- If the task threw an exception internally,
get()wraps it in anExecutionException. - If the calling thread is interrupted while waiting, throws
InterruptedException.
get() without a timeout can block indefinitely if the async task hangs or never completes. Use with care in production code.Method 5: `get(long timeout, TimeUnit unit)`
1V result = futureObj.get(3, TimeUnit.SECONDS);Like get() but with a maximum wait time. If the task does not complete within the timeout, throws TimeoutException.
After a TimeoutException, you can choose to:
- Log the timeout and move on
- Retry with
get()again - Cancel the task
Diagram: Future State Machine
Full Code Example: Future in Action
1import java.util.concurrent.*;2
3public class FutureDemo {4 public static void main(String[] args) throws Exception {5 // Create a thread pool with one thread6 ExecutorService pool = Executors.newFixedThreadPool(1);7
8 // Submit a task — takes 7 seconds to complete9 Future<?> futureObj = pool.submit(() -> {10 try {11 System.out.println("Task started by: " + Thread.currentThread().getName());12 Thread.sleep(7000); // simulate long computation13 System.out.println("Task completed!");14 } catch (InterruptedException e) {15 System.out.println("Task was interrupted.");16 }17 });18
19 // Non-blocking check immediately after submission20 System.out.println("Is task done? " + futureObj.isDone()); // false21
22 // Try to get result with 2-second timeout23 try {24 futureObj.get(2, TimeUnit.SECONDS); // task takes 7s, so this will time out25 } catch (TimeoutException e) {26 System.out.println("Timeout exception happened — task not done in 2 seconds.");27 }28
29 // Block indefinitely until task finishes30 futureObj.get(); // waits remaining ~5 seconds31
32 // Now the task is done33 System.out.println("Is task done now? " + futureObj.isDone()); // true34 System.out.println("Is task cancelled? " + futureObj.isCancelled()); // false35
36 pool.shutdown();37 }38}Expected Output
1Task started by: pool-1-thread-12Is task done? false3Timeout exception happened — task not done in 2 seconds.4Task completed!5Is task done now? true6Is task cancelled? falseStep-by-Step Execution
| Step | Thread | Action |
|---|---|---|
| 1 | main | Creates pool, submits task |
| 2 | pool-1-thread-1 | Starts executing task, sleeps 7s |
| 3 | main | isDone() → false (task still sleeping) |
| 4 | main | get(2, SECONDS) → blocks 2 seconds, then throws TimeoutException |
| 5 | main | Catches TimeoutException, prints message |
| 6 | main | get() → blocks until task finishes (≈5 more seconds) |
| 7 | pool-1-thread-1 | Wakes up, prints "Task completed!" |
| 8 | main | Unblocks, continues |
| 9 | main | isDone() → true, isCancelled() → false |
3. Callable Returning Values from Threads
The Gap in Runnable
Runnable has one method:
1@FunctionalInterface2public interface Runnable {3 void run(); // No return value4}This works for fire-and-forget tasks. But what if the async computation needs to produce a result?
Definition
Callable is a functional interface (in java.util.concurrent) that represents a task that:
- Can be executed by a thread
- Returns a result of type
V - Can throw a checked exception
1@FunctionalInterface2public interface Callable<V> {3 V call() throws Exception;4}Comparison: Runnable vs Callable
| Feature | Runnable | Callable |
|---|---|---|
| Method | void run() | V call() |
| Return type | None (void) | Generic type V |
| Throws checked exception | No | Yes |
Used with Future | Yes (result is null) | Yes (result is actual value) |
| Introduced in | Java 1.0 | Java 5 |
Runnable and Callable represent tasks to be executed. The only meaningful difference is whether the task produces a return value.4. Three Flavors of `submit()`
ExecutorService.submit() is overloaded with three signatures. Understanding each is essential.
Flavor 1: `submit(Runnable task)` No Result
1Future<?> future = pool.submit(() -> {2 System.out.println("Doing work, no return value.");3});- The task is a
Runnable— no return value. Future>uses a wildcard because there is no meaningful result type.- When you call
future.get(), it returnsnull(the framework hardcodesnullas the result forRunnabletasks). - You can still use
isDone(),isCancelled(),cancel().
1Object result = future.get(); // Returns null2System.out.println(result == null); // true? wildcard in Future> means "the result type is unknown/irrelevant." Since the task returns nothing, you capture it as Object or simply ignore the return.Flavor 2: `submit(Runnable task, T result)` Runnable with a Predefined Result
1List<Integer> output = new ArrayList<>(); // shared object2
3Future<List<Integer>> future = pool.submit(() -> {4 // Runnable modifies the shared object5 output.add(300);6}, output); // pass the object as the "result"- The second parameter
resultis returned byfuture.get()when the task completes. - The framework does not look at the
Runnable's internal logic to figure out the result — you hand it the object upfront. - The thread modifies that object during
run(). Since you hold a reference to the same object, you can read the updated state from either side.
1List<Integer> result = future.get(); // blocks until done2System.out.println(result.get(0)); // prints 3003System.out.println(output.get(0)); // also prints 300 — same referenceRunnable task "return" a value by mutating a shared object. It works but is less clean than using Callable.Flavor 3: `submit(Callable<T> task)` Clean Return Value
This is the cleanest and most common pattern when a task must return a computed value.
1Future<List<Integer>> future = pool.submit(() -> {2 List<Integer> result = new ArrayList<>();3 result.add(300);4 return result; // Callable returns value5});6
7List<Integer> result = future.get(); // blocks, then returns the list8System.out.println(result.get(0)); // prints 300- The lambda returns a value → Java infers it as
Callable.- >
Futurecaptures the exact return type.- >
- No shared mutable state needed.
Diagrams: Three Flavors
5. Internal Working: FutureTask
How `submit()` Works Internally
When you call pool.submit(runnable) or pool.submit(callable), the ThreadPoolExecutor does not execute the task directly. It wraps it inside a FutureTask.
FutureTask is the concrete class that:
- Implements
Runnable(so the executor can call.run()on it) - Implements
Future(so the caller can call.get(),.isDone(), etc.) - Internally maintains a state integer tracking task progress
- Stores the outcome (result or exception) once the task finishes
FutureTask Internal States
| State Value | Meaning |
|---|---|
0 — NEW | Task created, not yet started |
1 — COMPLETING | Task finished, result being set |
| 2 — NORMAL | Task completed normally |
3 — EXCEPTIONAL | Task threw an exception |
4 — CANCELLED | Task was canceled |
5 — INTERRUPTING | Cancel with interrupt in progress |
6 — INTERRUPTED | Thread was interrupted |
When a Runnable is submitted:
1submit(Runnable r) → new FutureTask(r, null) → queued in poolWhen a Callable is submitted:
1submit(Callable<T> c) → new FutureTask(c) → queued in poolThe pool's worker thread calls futureTask.run(), which in turn calls the underlying Runnable.run() or Callable.call(), captures the result, and transitions the state to NORMAL (or EXCEPTIONAL on failure).
6. CompletableFuture Advanced Async
Overview
CompletableFuture was introduced in Java 8 as part of java.util.concurrent. It is described as an "advanced version" of Future.
CompletableFuture extends the capabilities of Future by adding:
- Chaining of async operations (pipeline-style)
- Combining results of multiple futures
- Non-blocking callbacks instead of blocking
.get() - Manual completion (you can complete a future programmatically)
Class Hierarchy
CompletableFuture implements both Future and CompletionStage. Everything Future can do, CompletableFuture can do — plus much more.Default Thread Pool: ForkJoinPool
When you use CompletableFuture without providing a custom Executor, it internally uses the common ForkJoinPool (ForkJoinPool.commonPool()).
The common pool:
- Is shared across the JVM
- Dynamically sizes itself based on available CPU cores (typically
cores - 1threads) - You have no control over its min/max thread count
To gain control, always pass your own ExecutorService:
1ExecutorService pool = Executors.newFixedThreadPool(4);2CompletableFuture.supplyAsync(() -> "result", pool);7. CompletableFuture Methods In Depth
Method 1: `supplyAsync()` Start an Async Operation
Purpose
supplyAsync() is the entry point for starting an async computation that produces a result.
It is the CompletableFuture equivalent of pool.submit(callable).
Signatures
1// Uses ForkJoinPool.commonPool()2static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier)3
4// Uses the provided Executor5static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor)What is a `Supplier<U>`?
Supplier is a functional interface:
1@FunctionalInterface2public interface Supplier<T> {3 T get(); // No input, returns a value4}It represents a task that takes no input but produces an output — perfect for async computations.
Code Example
1import java.util.concurrent.*;2
3public class SupplyAsyncDemo {4 public static void main(String[] args) throws Exception {5 ExecutorService pool = Executors.newFixedThreadPool(2);6
7 CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {8 System.out.println("Running in: " + Thread.currentThread().getName());9 return "Task Completed";10 }, pool);11
12 // get() blocks main thread until result is available13 String result = cf.get();14 System.out.println("Result: " + result);15
16 pool.shutdown();17 }18}Output
1Running in: pool-1-thread-12Result: Task CompletedMethod 2: `thenApply()` and `thenApplyAsync()` Transform the Result
Purpose
After supplyAsync() finishes, thenApply() lets you apply a transformation to the result — similar to map() in Streams.
This enables chaining: the output of one stage becomes the input to the next.
Signatures
1// Synchronous — same thread as the previous stage2<U> CompletableFuture<U> thenApply(Function<? super T, ? extends U> fn)3
4// Asynchronous — new thread from common pool5<U> CompletableFuture<U> thenApplyAsync(Function<? super T, ? extends U> fn)6
7// Asynchronous — new thread from provided executor8<U> CompletableFuture<U> thenApplyAsync(Function<? super T, ? extends U> fn, Executor executor)Thread Behavior
| Method | Thread Used |
|---|---|
thenApply() | Same thread that completed the previous stage |
thenApplyAsync() | New thread from ForkJoinPool (or provided executor) |
Code Example `thenApply` (same thread)
1ExecutorService pool = Executors.newFixedThreadPool(2);2
3CompletableFuture<String> result = CompletableFuture4 .supplyAsync(() -> {5 System.out.println("supplyAsync thread: " + Thread.currentThread().getName());6 try { Thread.sleep(5000); } catch (InterruptedException e) {}7 return "Concept";8 }, pool)9 .thenApply(val -> {10 System.out.println("thenApply thread: " + Thread.currentThread().getName());11 return val + " and Coding";12 });13
14System.out.println(result.get());Output `thenApply`
1supplyAsync thread: pool-1-thread-12thenApply thread: pool-1-thread-13Concept and CodingBoth stages run on the same thread (pool-1-thread-1).
Code Example `thenApplyAsync` (new thread)
1CompletableFuture<String> result = CompletableFuture2 .supplyAsync(() -> {3 System.out.println("supplyAsync thread: " + Thread.currentThread().getName());4 try { Thread.sleep(5000); } catch (InterruptedException e) {}5 return "Concept";6 }, pool)7 .thenApplyAsync(val -> {8 System.out.println("thenApplyAsync thread: " + Thread.currentThread().getName());9 return val + " and Coding";10 });11
12System.out.println(result.get());Output `thenApplyAsync`
1supplyAsync thread: pool-1-thread-12thenApplyAsync thread: ForkJoinPool.commonPool-worker-13Concept and CodingA different thread picks up the thenApplyAsync stage.
thenApplyAsync uses your custom pool (not ForkJoinPool), pass the executor:
``java
.thenApplyAsync(val -> val + "!", pool)
``Chaining Multiple `thenApply`
1CompletableFuture<String> cf = CompletableFuture2 .supplyAsync(() -> "Hello")3 .thenApply(s -> s + " World")4 .thenApply(s -> s + "!")5 .thenApply(String::toUpperCase);6
7System.out.println(cf.get()); // HELLO WORLD!Each stage receives the result of the previous stage.
Method 3: `thenCompose()` and `thenComposeAsync()` Dependent Async Operations
Purpose
thenApply() transforms a value. But what if the next step itself is an async operation (returns a CompletableFuture)?
If you used thenApply() for that, you'd get CompletableFuture — a nested future. That's ugly and hard to work with.
thenCompose() flattens this nesting: it chains two async operations such that the second starts only when the first finishes, and returns a single CompletableFuture.
thenCompose is to CompletableFuture what flatMap() is to Stream or Optional.Signatures
1<U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)2
3<U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn)4
5<U> CompletableFuture<U> thenComposeAsync(Function<? super T, ? extends CompletionStage<U>> fn, Executor executor)Ordering Guarantee
thenCompose and thenComposeAsync guarantee ordering: the second async operation starts only after the first completes. Even with Async variants, the ordering is maintained.
Code Example
1ExecutorService pool = Executors.newFixedThreadPool(4);2
3CompletableFuture<String> result = CompletableFuture4 .supplyAsync(() -> "Hello", pool)5 .thenCompose(val ->6 CompletableFuture.supplyAsync(() -> val + " World", pool)7 )8 .thenCompose(val ->9 CompletableFuture.supplyAsync(() -> val + " All", pool)10 );11
12System.out.println(result.get()); // Always: Hello World AllChaining with `thenComposeAsync`
1CompletableFuture<String> result = CompletableFuture2 .supplyAsync(() -> "Hello", pool)3 .thenComposeAsync(val ->4 CompletableFuture.supplyAsync(() -> val + " World", pool), pool5 )6 .thenComposeAsync(val ->7 CompletableFuture.supplyAsync(() -> val + " All", pool), pool8 );9
10System.out.println(result.get()); // Always: Hello World AllthenCompose or thenComposeAsync you chain, the output order is always preserved. The framework internally maintains a stack of dependent actions.`thenApply` vs `thenCompose`
| Aspect | thenApply | thenCompose |
|---|---|---|
| Input function type | Function | Function |
| Next step is async? | No | Yes |
| Risk of nesting? | No | Yes (without compose) |
| Ordering guaranteed? | Same-thread only | Always |
| Analogy | Stream.map() | Stream.flatMap() |
Method 4: `thenAccept()` and `thenAcceptAsync()` End of Chain
Purpose
thenAccept() is a terminal operation in a CompletableFuture chain. It receives the result of the previous stage but does not return a value.
It is used for side effects: logging, printing, writing to a database, etc.
Signature
1CompletableFuture<Void> thenAccept(Consumer<? super T> action)2CompletableFuture<Void> thenAcceptAsync(Consumer<? super T> action)Why Is It "Terminal"?
The return type is CompletableFuture. Since Void has no meaningful value, you cannot meaningfully chain further with thenApply or thenCompose.
thenAccept, it's semantically incorrect because there's no result to pass to the next stage. Treat it as the end of the pipeline.Code Example
1CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> "Hello", pool);2
3CompletableFuture<Void> end = cf.thenAccept(val -> {4 System.out.println("Received: " + val); // Received: Hello5 // No return — this is Void6});7
8end.get(); // Wait for the terminal stage to completeOutput
1Received: HelloMethod 5: `thenCombine()` and `thenCombineAsync()` Merge Two Futures
Purpose
thenCombine() is used when you have two independent async tasks running in parallel, and you want to combine their results once both are finished.
1Task 1 ──────────────────► result1 ─┐2 ├─► combine ──► final result3Task 2 ──────────────────► result2 ─┘Signature
1<U, V> CompletableFuture<V> thenCombine(2 CompletionStage<? extends U> other,3 BiFunction<? super T, ? super U, ? extends V> fn4)other— The secondCompletableFutureto combine withfn— ABiFunctionthat takes both results and produces a combined output
Code Example
1ExecutorService pool = Executors.newFixedThreadPool(4);2
3CompletableFuture<Integer> task1 = CompletableFuture4 .supplyAsync(() -> {5 System.out.println("Task1 thread: " + Thread.currentThread().getName());6 return 10;7 }, pool);8
9CompletableFuture<String> task2 = CompletableFuture10 .supplyAsync(() -> {11 System.out.println("Task2 thread: " + Thread.currentThread().getName());12 return "K";13 }, pool);14
15// Combine: integer + string → string16CompletableFuture<String> combined = task1.thenCombine(task2, (num, str) -> num + str);17
18System.out.println("Combined result: " + combined.get()); // 10K19
20pool.shutdown();Output
1Task1 thread: pool-1-thread-12Task2 thread: pool-1-thread-23Combined result: 10KNote: Both tasks run in parallel on separate threads. thenCombine waits until both are done, then calls the BiFunction.
Complete Pipeline Diagram
Summary Table: All CompletableFuture Methods
| Method | Input | Output | Thread | Use Case |
|---|---|---|---|---|
supplyAsync() | Supplier | CF | New (pool) | Start async operation |
thenApply() | Function | CF | Same | Transform result synchronously |
thenApplyAsync() | Function | CF | New | Transform result asynchronously |
thenCompose() | Function | CF | Same | Chain dependent async ops |
thenComposeAsync() | Function | CF | New | Chain with ordering, new thread |
thenAccept() | Consumer | CF | Same | Terminal: consume result |
thenAcceptAsync() | Consumer | CF | New | Terminal: consume async |
thenCombine() | Two CFs + BiFunction | CF | Same | Merge two parallel results |
thenCombineAsync() | Two CFs + BiFunction | CF | New | Merge two parallel results async |
8. Interview Notes
Q1: What is the difference between `Future` and `CompletableFuture`?
| Aspect | Future | CompletableFuture |
|---|---|---|
| Java version | Java 5 | Java 8 |
| Blocking | get() is always blocking | Can use callbacks (non-blocking) |
| Chaining | Not supported | Fully supported |
| Combining futures | Not supported | thenCombine(), etc. |
| Manual completion | Not possible | complete(), completeExceptionally() |
| Exception handling | Only via ExecutionException | exceptionally(), handle() |
Q2: What is `FutureTask` and how does it relate to `Future`?
FutureTask is the concrete implementation of the Future interface. It implements RunnableFuture, which extends both Runnable and Future. When you call pool.submit(callable), the executor wraps it in a FutureTask internally.
Q3: What is the difference between `thenApply` and `thenCompose`?
thenApplyis used when the next transformation is a plain value (not async).thenComposeis used when the next step itself returns aCompletableFuture— it flattens the nesting.thenApplyis analogous toStream.map();thenComposeis analogous toStream.flatMap().
Q4: What thread runs `thenApply` vs `thenApplyAsync`?
thenApply→ same thread that completed the previous stage.thenApplyAsync→ a new thread (fromForkJoinPoolor your provided executor).
Q5: What happens if you call `get()` and the task throws an exception?
The exception is wrapped in a java.util.concurrent.ExecutionException. You must catch it and call .getCause() to get the original exception.
1try {2 future.get();3} catch (ExecutionException e) {4 Throwable original = e.getCause();5}Q6: Why does `cancel()` sometimes return `false`?
- The task is already completed — nothing to cancel.
- The task is already canceled.
- The thread could not be interrupted (
mayInterruptIfRunningwasfalseand the task already started).
Q7: What is the default thread pool used by `CompletableFuture`?
ForkJoinPool.commonPool(). It's a shared pool across the JVM. For production code with predictable performance, always pass a custom ExecutorService.
Q8: What is the difference between `Callable` and `Supplier`?
| Aspect | Callable | Supplier |
|---|---|---|
| Package | java.util.concurrent | java.util.function |
| Method | call() | get() |
| Checked exception | Yes (throws Exception) | No |
| Used with | ExecutorService.submit() | CompletableFuture.supplyAsync() |
9. Common Mistakes
Mistake 1: Calling `get()` immediately after `submit()`
1Future<String> f = pool.submit(() -> {2 Thread.sleep(5000);3 return "done";4});5String result = f.get(); // Blocks immediately — defeats the purpose of async!✅ Correct approach: Do other work first, then call get() only when you actually need the result.
Mistake 2: Ignoring `TimeoutException`
1f.get(2, TimeUnit.SECONDS); // May throw TimeoutException — must handle it!✅ Always wrap timed get() in a try-catch for TimeoutException.
Mistake 3: Using `thenApply` when the function returns a `CompletableFuture`
1// WRONG — results in CompletableFuture<CompletableFuture<String>>2CompletableFuture<CompletableFuture<String>> bad = cf.thenApply(val ->3 CompletableFuture.supplyAsync(() -> val + "!")4);✅ Use thenCompose to flatten:
1CompletableFuture<String> good = cf.thenCompose(val ->2 CompletableFuture.supplyAsync(() -> val + "!")3);Mistake 4: Not shutting down the `ExecutorService`
1ExecutorService pool = Executors.newFixedThreadPool(4);2// ... use pool ...3// Forgot pool.shutdown() — JVM never exits!✅ Always call pool.shutdown() (or pool.shutdownNow()) when done.
Mistake 5: Assuming ordering with `thenApplyAsync` chaining
When using thenApplyAsync across multiple stages without thenCompose, there is no ordering guarantee between dependent async stages.
✅ Use thenCompose / thenComposeAsync for dependent ordered operations.
10. Best Practices
- Always use a custom Executor with
CompletableFuturein production. The commonForkJoinPoolis shared and can starve.
- Prefer
Callableover theRunnable + shared objectworkaround when the task must return a result.
- Use
thenAcceptas the terminal stage of a pipeline — do not try to chain after it.
- Use
thenComposefor dependent async tasks to ensure ordering and avoid nestedCompletableFuture.
- Handle exceptions explicitly using
exceptionally()orhandle()onCompletableFutureinstead of catching only inget().
1CompletableFuture<String> cf = CompletableFuture2 .supplyAsync(() -> { throw new RuntimeException("Oops!"); })3 .exceptionally(ex -> "Fallback value: " + ex.getMessage());4
5System.out.println(cf.get()); // Fallback value: Oops!- Use
thenCombinefor truly independent parallel tasks that need their results merged.
- Avoid
get()without timeout in latency-sensitive paths.
11. Practice Questions
Easy
- What is
Futurein Java? What interface does it belong to? - List all five methods of the
Futureinterface and describe each. - What is the return type of
ExecutorService.submit(Runnable)? - What is the difference between
RunnableandCallable? - What does
isDone()return when a task is canceled?
Medium
- Write a program that submits three
Callabletasks to a thread pool, waits for all of them usingFuture.get(), and prints each result. - Explain what happens step-by-step when
future.get(2, TimeUnit.SECONDS)is called and the task takes 5 seconds. - Write a
CompletableFuturechain that: (a) fetches a user name asynchronously, (b) converts it to uppercase, (c) prints the result. - What is
FutureTask? How does it relate to bothRunnableandFuture? - What thread executes
thenApplyif the previoussupplyAsyncused a custom thread pool?
Hard
- Implement two independent async computations using
CompletableFuture, then combine their results withthenCombine. One returns a price (Double), the other returns a currency symbol (String). Combine them as"$25.00". - Explain the difference between
thenApply,thenCompose, andthenCombinewith a concrete use case for each. - What are the risks of using
ForkJoinPool.commonPool()in a web application? How do you mitigate them? - Write a pipeline where Step 1, Step 2, and Step 3 are all async but strictly ordered using
thenComposeAsync. Verify the ordering by printing thread names and sequence numbers. - What happens when you call
cancel(true)on aFuturewhose task is already sleeping inThread.sleep()? Walk through the exception flow.
12. Summary
Revision Bullets
Futureprovides a handle to track an async task — check status, retrieve result, cancel.- Five methods:
cancel(),isCancelled(),isDone(),get(),get(timeout, unit). Runnablereturns nothing.Callablereturns a value of typeV.- Three
submit()overloads: Runnable (result = null), Runnable + T (result = pre-set object), Callable (result = computed value). - Internally,
submit()wraps tasks inFutureTask, which implements bothRunnableandFuture. CompletableFutureis the advanced version ofFuture— supports chaining, combining, non-blocking callbacks.supplyAsync()starts an async task; uses ForkJoinPool by default; pass your own Executor for control.thenApply()= synchronous transform on same thread;thenApplyAsync()= async transform on new thread.thenCompose()= chain dependent async operations with guaranteed ordering; analogous toflatMap.thenAccept()= terminal consumer stage; returnsCompletableFuture.thenCombine()= merge results of two independent parallel futures with aBiFunction.- In production: always use a custom
ExecutorServicewithCompletableFuture, always handleExecutionException, always shut down your pools.
End of Chapter — Future, Callable & CompletableFuture
Mastery check
How well can you recall this?
Finished this lesson?