nus-cs2030 / 2021-s2

2 stars 2 forks source link

thenApplyAsync vs thenApply #388

Closed lokehsienjie closed 3 years ago

lokehsienjie commented 3 years ago

Hi! Would just like to see if anyone can shed some light on when we use thenApplyAsync versus thenApply? Understand from the API that thenApplyAsync (or any then____Async) will execute using this stage's default asynchronous execution facility, whereas thenApply just executes. My understanding of this is that thenApplyAsync simply branch out to more threads that runs asynchronously from this point of execution on. However, since the CompletableFuture object is already being executed on a asynchronous thread, when is it important for us to use thenApplyAsync, and when is it better to use thenApply? Thank you! image

Qingyi1115 commented 3 years ago

Hi Hsien Jie! thenApplyAsync allows multiple task to run at the same times, so let's say method 1 uses thenApply, and method 2 uses thenApplyAsync. We can call method 2 multiple times, and it will be executed in different threads. I tink :P

liongthryan commented 3 years ago

I found a helpful post that explains this concept well!

https://stackoverflow.com/questions/47489338/what-is-the-difference-between-thenapply-and-thenapplyasync-of-java-completablef#:~:text=thenApply(fn)%20%2D%20runs%20fn,defined%20executor%20regardless%20of%20circumstances.

The question asked there is similar to yours, and I think the answers are all useful and descriptive. Hope this helps!

lokehsienjie commented 3 years ago

@Qingyi1115 ohh i see, thanks for the perspective!! @liongthryan ahh nice this was rly useful in understanding the concept of the context. Thank you!