Lesson 5 of 8
CompletableFuture - Async Programming
CompletableFuture (Java 8+) enables non-blocking, composable async pipelines. Instead of blocking with Future.get(), you chain callbacks that run when results are available. It's the foundation of reactive-style Java programming without a framework.
CompletableFuture Pipelines
import java.util.concurrent.*;
import java.util.function.*;
public class CompletableFutureDemo {
public static void main(String[] args) throws Exception {
// Start async computation (runs in ForkJoinPool.commonPool by default)
CompletableFuture<List<Book>> catalogFuture = CompletableFuture
.supplyAsync(() -> loadFromDatabase()); // Supplier<T>
// Chain transformations (non-blocking - callbacks registered, not waited)
CompletableFuture<List<String>> titlesFuture = catalogFuture
.thenApply(books -> books.stream()
.map(Book::getTitle)
.toList()); // Function<T,R>
// Side effect (like Consumer)
CompletableFuture<Void> printFuture = titlesFuture
.thenAccept(titles -> titles.forEach(System.out::println)); // Consumer<T>
// Error handling
CompletableFuture<List<Book>> safeLoad = CompletableFuture
.supplyAsync(() -> loadFromDatabase())
.exceptionally(ex -> {
System.err.println("Load failed: " + ex.getMessage());
return List.of(); // fallback: return empty list on error
});
// whenComplete - runs after completion (success OR failure)
safeLoad.whenComplete((books, ex) -> {
if (ex != null) System.err.println("Error: " + ex.getMessage());
else System.out.println("Success: " + books.size() + " books loaded");
});
// Combine two futures - thenCombine: when BOTH complete
CompletableFuture<String> nameF = CompletableFuture.supplyAsync(() -> "Alice");
CompletableFuture<Integer> scoreF = CompletableFuture.supplyAsync(() -> 95);
CompletableFuture<String> result = nameF.thenCombine(scoreF,
(name, score) -> name + " scored " + score);
System.out.println(result.get()); // "Alice scored 95"
// Run multiple futures in parallel, wait for ALL
CompletableFuture<List<Book>> f1 = CompletableFuture.supplyAsync(() -> loadFromDatabase());
CompletableFuture<List<Book>> f2 = CompletableFuture.supplyAsync(() -> loadFromCache());
CompletableFuture<Void> allDone = CompletableFuture.allOf(f1, f2);
allDone.thenRun(() -> System.out.println("Both completed"));
// Get first to complete
CompletableFuture<String> first = CompletableFuture.anyOf(
CompletableFuture.supplyAsync(() -> { sleep(200); return "Slow"; }),
CompletableFuture.supplyAsync(() -> { sleep(50); return "Fast"; })
).thenApply(Object::toString);
System.out.println(first.get()); // "Fast"
// Custom executor (use for I/O-bound tasks - don't saturate commonPool)
ExecutorService ioPool = Executors.newFixedThreadPool(10);
CompletableFuture<String> customAsync = CompletableFuture
.supplyAsync(() -> readFromFile(), ioPool)
.thenApplyAsync(content -> content.toUpperCase(), ioPool);
printFuture.join(); // wait for the original chain
ioPool.shutdown();
}
static List<Book> loadFromDatabase() { return new java.util.ArrayList<>(); }
static List<Book> loadFromCache() { return new java.util.ArrayList<>(); }
static String readFromFile() { return "content"; }
static void sleep(int ms) { try { Thread.sleep(ms); } catch (Exception e) {} }
}Quick Quiz
Tip
Tip
Practice CompletableFuture Async Programming in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for CompletableFuture - Async Programming
Practice Task
Note
Practice Task - (1) Write a working example of CompletableFuture Async Programming from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with CompletableFuture Async Programming is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Finished this lesson?