nus-cs2030 / 2223-s1

MIT License
1 stars 0 forks source link

PYP Q5b CompletableFuture #313

Closed ziyi105 closed 1 year ago

ziyi105 commented 1 year ago

image can i check that when .join is executed, will all the half-finished expressions be executed synchronously or asynchronously? If i understand correctly, the objective of this question is so that 1+2 and 3+4 can be computed at the same time (two threads). To create two threads, isnt it more reasonable to use thenCombineAsync?

junhuiii commented 1 year ago

At this point in the video, Prof Chia hasn't made the code asynchronous yet. You are right that the objective is to evaluate the half-finished expressions simultaneously. That is why afterwards in the video, Prof Chia used CompletableFuture.supplyAsync(() -> cf1.thenCombine(cf2, (x,y) -> add(x,y)).join(); for both the add and multiply portions in order to ensure that the computations are run on separate threads.

ziyi105 commented 1 year ago

I see. Then can I use thenCombineAsync instead of supplyAsync?

junhuiii commented 1 year ago

Yup, I think you can. Just make sure to not do a join() at the end of the statement as you want to get a CompletableFuture<Integer> back.

ziyi105 commented 1 year ago

alright thank you so much!