Completable Futures - thenApply vs thenCompose
January 6, 2024
Let’s wrap a blocking operation in a CompletablFuture
|
|
Here we chain the outputs so that it prints the aggregated results. But this will print the future not the value (16)
|
|
But I want to return 16 as output but not wrapped in a CompletableFuture.
Solution: simply replace thenApply with thenCompose
|
|
Notes
Non-blocking operations may run in main thread or in a background thread depending on the duration of the operation!
runAsync- For fire and forget taskssupplyAsync- Get a response back from the task - by default uses the ForkJoin poolthenApply- Just like themapmethod inStreamAPIthenCompose- Aanalogous toflatMapmethod inStreamAPI