|
|
CompletableFuture
Author: Venkata Sudhakar
CompletableFuture is a Java 8 class for asynchronous programming that supports functional composition, chaining, and combining multiple async operations. It implements both Future and CompletionStage interfaces. Key Methods: 1. supplyAsync() - Runs a task asynchronously and returns a result. 2. thenApply() - Transforms the result when it is available. 3. thenAccept() - Consumes the result with no return value. 4. thenCombine() - Combines two independent futures. 5. exceptionally() - Handles exceptions in the async pipeline. The below example shows how to use CompletableFuture for async programming in Java 8.
It gives the following output,
Task running in: ForkJoinPool.commonPool-worker-1
Result: Hello from async task
Word count: 4
Full name: John Doe
Recovered from: java.lang.RuntimeException: Something went wrong!
Task 1 done, Task 2 done, Task 3 done
CompletableFuture vs Future: Future - Basic async result holder. Can only check isDone() or blocking get(). No chaining or composition. CompletableFuture - Supports chaining (thenApply, thenCompose), combining (thenCombine, allOf), exception handling (exceptionally, handle), and non-blocking callbacks (thenAccept).
|
|