Java CompletableFuture: Asynchronous Programming Guide
Java's CompletableFuture, introduced in Java 8, replaces the blocking Future with a rich, non‑blocking API that supports asynchronous task creation, result retrieval via get/join, chaining callbacks, exception handling, task combination (AND/OR, allOf/anyOf), and recommends custom executors, timeouts, and proper saturation policies.
This article explains Java's CompletableFuture, a powerful tool for asynchronous programming introduced in Java 8. It overcomes the limitations of the older Future interface by providing non‑blocking result retrieval and rich callback APIs.
It begins with a review of Future, showing how Future.get() blocks the thread and how CountDownLatch can be used to wait for multiple tasks, but the approach is cumbersome.
The article then introduces CompletableFuture, demonstrating its creation via CompletableFuture.supplyAsync and CompletableFuture.runAsync (with or without a custom Executor), and explains the four ways to obtain results: get() , get(timeout, unit) , getNow(valueIfAbsent) , and join() .
Further sections cover asynchronous callbacks: thenRun / thenRunAsync for chaining void‑returning tasks, thenAccept / thenAcceptAsync for consuming results, and thenApply / thenApplyAsync for transforming results. Code examples illustrate each pattern.
Exception handling is discussed with whenComplete and exceptionally , showing how to react to both normal completion and exceptions, and emphasizing that calling get() or join() is required to surface exceptions.
The piece also details task combination logic: AND relationships ( thenCombine , thenAcceptBoth , runAfterBoth ), OR relationships ( applyToEither , acceptEither , runAfterEither ), and multi‑task synchronizers allOf and anyOf , complete with sample code.
Finally, it outlines best practices: always retrieve results to expose exceptions, use timeouts with get() , prefer custom thread pools over the default ForkJoinPool, and choose an appropriate saturation policy (e.g., AbortPolicy ) when configuring pools.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.