LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 8

Combining two futures with thenCombine Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 8 Back to Exercise

What is the output of the following Java program?

Main.java
import java.util.concurrent.CompletableFuture;

public class Main {
    public static void main(String[] args) {
        CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> 1200);
        CompletableFuture<Integer> qty = CompletableFuture.supplyAsync(() -> 3);
        CompletableFuture<Double> taxRate = CompletableFuture.completedFuture(0.18);
        double total = price.thenCombine(qty, (p, q) -> p * q)
                            .thenCombine(taxRate, (sub, t) -> sub * (1 + t))
                            .join();
        System.out.println(total);
    }
}
  • A 4248.0 Correct
  • B 3600.0
  • C 4248
  • D 1416.0
Correct Answer: Option A

1200 × 3 = 3600, plus 18% = 4248.0. completedFuture creates an already-finished future.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links