CompletableFutures: A Primer
CompletableFutures are constructs in Java that are very useful for writing clean, concurrent code. Most of the methods around CompletableFutures return stages, which represent asynchronous tasks that can trigger other stages, or return values in the future.
Three of the most useful methods in CompletableFutures are:
- thenAccept: Takes the result of a previous CompletionStage, does something with it, and returns a void CompletableFuture.
- thenApply: Takes the result of a previous CompletionStage and applies a function to it. This method behaves analogously to a map operation.
- thenCompose: Takes the result of a previous CompletionStage and asynchronously applies a function to it. This method behaves analogously to a flatmap operation.
It’s easy to mix up thenCompose and thenApply. This thread on StackOverflow helps to shed some light on the differences.
Comments