Question 9
Back to Exercise
What is the output of the following Java program?
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
List<CompletableFuture<Integer>> parts = List.of(
CompletableFuture.supplyAsync(() -> 10),
CompletableFuture.supplyAsync(() -> 20),
CompletableFuture.supplyAsync(() -> 30));
CompletableFuture<Void> all = CompletableFuture.allOf(parts.toArray(new CompletableFuture<?>[0]));
int sum = all.thenApply(v -> parts.stream().mapToInt(CompletableFuture::join).sum()).join();
System.out.println(sum + " " + all.isDone() + " " + parts.get(1).join());
}
}
- A 60 true 20 Correct
- B 60 false 20
- C 0 true 20
- D 30 true 20
Correct Answer: Option A
allOf completes when every part is done (its own result is Void); then each part can be joined without blocking.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!