Closed tomjoju closed 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.
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.
Alright, thanks @bryanwee023 and @kaiyang96! I got it!
Description
Hi guys, just had a query about the
anyOf
andallOf
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:CompletableFuture.anyOf()
method? Specifically, will there be situations where 2 and 3 will be printed?CompletableFuture.anyOf()
was changed toCompletableFuture.allOf()
in line 3?Topic:
CompletableFuture.anyOf()
vsCompletableFuture.allOf()
Screenshots (if any):