nus-cs2030 / 2021-s2

2 stars 2 forks source link

.join() after completable future #128

Open eryuanren opened 3 years ago

eryuanren commented 3 years ago

Hi, in the lecture, prof had to create a new CompletableFuture cf and then cf.join() to obtain the value. I was wondering if just adding a .join() after Completable.Future.supplyAsync(() -> task(5)) works. and if not, why does it not work. Thank you!

g4ryy commented 3 years ago

Hi, yes this works but you would have to wait for the asynchronous task to complete before you can run other tasks. What prof did allows us to run other tasks at the same time while waiting for completion.

High325 commented 3 years ago

The code would compile and it would work. However, adding .join() immediately after the CompletableFuturedefeats the purpose of running a CompletableFuture. Using CompletableFuture allows the code to continue processing other tasks(i.e. calling other methods or running other lines of code) while your CompletableFuture is being run. .join() would force the CompletableFuture task to complete running before proceeding with the rest of your code.

markwty commented 3 years ago

The join() is used typically when the return result from the thread is needed for the next block of code on the main thread to run. For example, like when designing a UI, the UI is typically on the main thread and a thread to request some information from the online database such as the inventory is initiated. You will not want to join() immediately since it will render the user unable to scroll or click on anything on the UI until the thread returns. And also since the thread varies in the time it takes to execute, it is good to ensure there is a result using a join() when it is really needed.