Sub topic 1
Why Future Is Not Enough
Prerequisites
Assume you know Java 8 lambdas, method references, generics, ExecutorService, and checked versus unchecked exceptions.
Why `Future` Is Not Enough
Future<T> represents a result that may become available later. It can start work and let you call get(), but it offers little support for describing the next step.
Calling get() blocks the current thread until the result is ready. You must also manage separate tasks yourself when one task depends on another. Future has no direct operation for “when this finishes, transform its value.”
CompletableFuture<T> is both a future result and a pipeline of completion stages. Each stage describes work that follows another stage.
Creating a `CompletableFuture`
Use supplyAsync when background work returns a value. Use runAsync when it only performs an action. Use completedFuture when a value is already available.
import java.util.concurrent.CompletableFuture;
public class Basics {
public static void main(String[] args) {
CompletableFuture<String> future =
CompletableFuture.supplyAsync(() -> "hello");
CompletableFuture<Void> printed = future
.thenApply(String::toUpperCase)
.thenAccept(System.out::println);
printed.join();
CompletableFuture<Void> task =
CompletableFuture.runAsync(() -> System.out.println("working"));
task.join();
CompletableFuture<String> ready =
CompletableFuture.completedFuture("already available");
System.out.println(ready.join());
}
}By default, asynchronous methods use the common fork-join pool. Later, you can pass an explicit executor when the work needs controlled threads.
> callout note > A CompletableFuture describes a computation. Creating one does not mean that its result is immediately available.
Getting the Result: `join` Versus `get`
Both methods wait for completion. get() declares checked exceptions, so callers must catch or declare InterruptedException and ExecutionException. join() throws unchecked CompletionException when the computation fails. It is often simpler inside a completion pipeline.
Use blocking retrieval at the application boundary when necessary. Prefer dependent stages inside asynchronous code.
Transforming Results
thenApply maps a value to another value. thenAccept consumes a value and returns CompletableFuture<Void>.
The non-Async forms may run the continuation on the thread that completes the previous stage. They do not automatically create a new thread.
Exercise
Which method should transform "hello" into "HELLO", and which should print the transformed value?
Show answer
Use thenApply(String::toUpperCase) to transform it, followed by thenAccept(System.out::println) to consume it.