Chapter 16. CompletableFuture: composable asynchronous programming
This chapter covers
- Creating an asynchronous computation and retrieving its result
- Increasing throughput by using nonblocking operations
- Designing and implementing an asynchronous API
- Consuming asynchronously a synchronous API
- Pipelining and merging two or more asynchronous operations
- Reacting to the completion of an asynchronous operation
Chapter 15 explored the modern concurrency context: that multiple processing resources (CPU cores and the like) are available, and you want your programs to exploit as many of these resources as possible in a high-level manner (rather than litter your programs with ill-structured, unmaintainable operations on threads). We noted that parallel streams and fork/join parallelism provide higher-level constructs for expressing parallelism in programs iterating over collections and in programs involving divide-and-conquer, but that method invocations provide additional opportunities for executing code in parallel. Java 8 and 9 introduce two specific APIs for this purpose: CompletableFuture and the reactive-programming paradigm. This chapter explains, through practical code examples, how the Java 8 CompletableFuture implementation of the Future interface gives you additional weapons in your programming armory. It also discusses additions introduced in Java 9.