LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 10

Chaining async lookups with thenCompose Answer, explanation & discussion

  • Output
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 10 Back to Exercise

What is the output of the following Java program?

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

public class Main {
    static final Map<String, Integer> USER_IDS = Map.of("asha", 7);
    static final Map<Integer, String> CITY_OF = Map.of(7, "Pune");

    static CompletableFuture<Integer> idOf(String user) { return CompletableFuture.supplyAsync(() -> USER_IDS.getOrDefault(user, -1)); }
    static CompletableFuture<String> cityOf(int id) { return CompletableFuture.supplyAsync(() -> CITY_OF.getOrDefault(id, "unknown")); }

    public static void main(String[] args) {
        String a = idOf("asha").thenCompose(Main::cityOf).join();
        String b = idOf("ravi").thenCompose(Main::cityOf).join();
        CompletableFuture<CompletableFuture<String>> nested = idOf("asha").thenApply(Main::cityOf);
        System.out.println(a + " " + b + " " + nested.join().join());
    }
}
  • A Pune unknown Pune Correct
  • B Pune Pune Pune
  • C 7 -1 Pune
  • D Compilation error
Correct Answer: Option A

thenCompose flattens one async step into the next; thenApply with an async function leaves a nested future that needs two joins.

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