nus-cs2030 / 2021-s1

27 stars 48 forks source link

AY 19/20 Sem 2 Qn #540

Closed tomjoju closed 3 years ago

tomjoju commented 3 years ago

Description

Hi guys, just had a query about the anyOf and allOf methods in CompletableFuture. Particularly, for the question below, I know that 4 will definitely have to be printed AFTER either 2 or 3. Regarding this, I had 2 queries:

  1. Does the unfinished thread continue running even when the other thread is finished in the CompletableFuture.anyOf() method? Specifically, will there be situations where 2 and 3 will be printed?
  2. How will the behaviour change if CompletableFuture.anyOf() was changed to CompletableFuture.allOf() in line 3?

Topic:

CompletableFuture.anyOf() vs CompletableFuture.allOf()

Screenshots (if any):

Capture

bryanwee023 commented 3 years ago

I think it is possible both 2 and 3 are printed as long as the main program does not terminate before the later one finishes.

If we use allOf(), I think the following are all possible: 2, 3, 4 3, 2, 4 Where 4 is only printed after both 2 and 3 prints.

kaiyang96 commented 3 years ago

As for the first question, the thenRun method is called once any of the previous CompletableFutures were completed, and the join method only detects if the thread referenced in thenRun is dead. Assuming printAsync(x) means it will take x seconds to print x, in this case, 2 will be printed first, allowing the printing of 4 to start, and 3 will be printed during the printing of 4. However if you did something like CompletableFuture.anyOf(printAsync(2), printAsync(10)).thenRun(() -> printAsync(4)).join(), you should only get 2, 4 as the thread dies before 10 is printed out.

Meanwhile if you switched out anyOf for allOf, the thenRun method is only called once all previous CompletableFutures have completed or reached an exception.

tomjoju commented 3 years ago

Alright, thanks @bryanwee023 and @kaiyang96! I got it!