LearnFrenzy
Sign in Take a free test

Concurrency and Executors · Predict the Output · Question 6

Recovering with exceptionally Answer, explanation & discussion

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

What is the output of the following Java program?

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

public class Main {
    static CompletableFuture<Integer> parse(String s) {
        return CompletableFuture.supplyAsync(() -> Integer.parseInt(s))
            .thenApply(n -> n * 2)
            .exceptionally(ex -> -1);
    }

    public static void main(String[] args) {
        System.out.println(parse("21").join() + " " + parse("abc").join() + " " + parse("5").thenApply(n -> n + 100).join());
    }
}
  • A 42 -1 110 Correct
  • B 42 -2 110
  • C 21 -1 105
  • D CompletionException
Correct Answer: Option A

A failure skips thenApply and goes straight to exceptionally, which supplies -1.

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