Member-only story

Choosing between thenApply and thenApplyAsync in CompletableFuture

Namrata
4 min readMar 13, 2024

--

Java’s CompletableFuture class provides two key methods, thenApply and thenApplyAsync, for processing the results of asynchronous computations. While both methods serve the same purpose, their subtle differences can significantly impact the performance and concurrency of your program. This article explores the distinctions between thenApply and thenApplyAsync, offering insights into when to use each based on the specific requirements of your application.

Photo by Chuck G on Unsplash

`thenApply` and `thenApplyAsync` are both methods in Java’s CompletableFuture class, and they’re used to process the result of a computation when it becomes available. However, there are key differences between them that can impact the performance and behavior of your program.

1. Execution Thread: The main difference between `thenApply` and `thenApplyAsync` is the thread they’re executed on. `thenApply` executes the callback function on the same thread that completed the previous CompletableFuture, while `thenApplyAsync` executes the callback function on a different thread obtained from the ForkJoinPool.commonPool() (default) or a given Executor.

2. Non-blocking: `thenApplyAsync` is non-blocking. It can offload the subsequent completion stage to some other thread, allowing the current thread to do other work in the meantime. This…

--

--

Namrata
Namrata

Written by Namrata

Engineering @Microsoft A software developer writing her daily bits . https://www.linkedin.com/in/namrataagarwal5/

No responses yet