Sub topic 2
Creating a CompletableFuture
This chapter assumes you know Java 8 lambdas, method references, generics, functional interfaces, and basic ExecutorService use. A CompletableFuture<T> represents a possible result of type T that may become available later. You can create one for work that runs asynchronously or for a value that already exists.
Three common ways to create a future
Use supplyAsync when the task produces a value. Its lambda is a Supplier<T>, so it takes no argument and returns a result.
Use runAsync when the task performs an action but produces no value. Its lambda is a Runnable.
Use completedFuture when the result is already available. This method creates a future that is complete immediately.
| Method | Lambda type | Result |
|---|---|---|
| `supplyAsync` | `Supplier<T>` | A value of type `T` |
| `runAsync` | `Runnable` | `Void` |
| `completedFuture` | None | An existing value |
The following program shows all three methods:
import java.util.concurrent.CompletableFuture;
public class Creating {
public static void main(String[] args) {
CompletableFuture<String> message =
CompletableFuture.supplyAsync(() -> "hello");
CompletableFuture<Void> logTask =
CompletableFuture.runAsync(() ->
System.out.println("background action"));
CompletableFuture<Integer> cachedValue =
CompletableFuture.completedFuture(42);
System.out.println(message.join());
logTask.join();
System.out.println(cachedValue.join());
}
}message eventually contains "hello". logTask completes after printing its message, but it has no meaningful result. cachedValue is already complete when it is created.
What happens inside `supplyAsync`
When you call supplyAsync, Java submits the supplier to an executor. If you do not provide an executor, the task normally uses the common ForkJoinPool. The method returns immediately with a CompletableFuture.
The task might still be running when the next line executes. The future records its eventual state:
- It may complete normally with a value.
- It may complete exceptionally if the supplier throws an exception.
- It may be cancelled.
A future does not make the task itself faster. It gives your program an object that represents the task and its eventual outcome.
Supplying an executor
The overloads that accept an Executor let you choose where the task runs. This is important when the work blocks on files, databases, or network calls. A dedicated pool can prevent that work from competing with unrelated tasks in the common pool.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CustomExecutor {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<String> future =
CompletableFuture.supplyAsync(() -> "loaded", pool);
System.out.println(future.join());
} finally {
pool.shutdown();
}
}
}The finally block shuts down the executor even if the task or result handling fails. Do not create a new executor for every small task. Reuse a deliberately sized pool and manage its lifetime.
A future created by supplyAsync is not automatically a complete application workflow. It only represents the first asynchronous operation. Later stages can describe what should happen after that operation finishes.
Exercise
Which creation method should you use for a task that writes an audit record and returns no result?
Show answer
Use runAsync, because the task performs an action and does not produce a value.