Java SE 8 Programmer II Exam: Result Analysis

Java SE 8 Programmer II Exam

Question

Given the code fragments: class Caller implements Callable<String>{ String str; public Caller (String s) {this.str=s;} public String call()throws Exception { return str.concat ("Caller");} } class Runner implements Runnable{ String str; public Runner (String s) {this.str=s;} public void run () { System.out.println (str.concat ("Runner"));} } and public static void main (String[] args) InterruptedException, ExecutionException{ ExecutorService es = Executors.newFixedThreadPool(2); Future f1 = es.submit (new Caller ("Call")); Future f2 = es.submit (new Runner ("Run")); String str1 = (String) f1.get(); String str2 = (String) f2.get();//line n1 System.out.println(str1+ ":" + str2); } What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The given code creates two classes: Caller which implements Callable interface, and Runner which implements Runnable interface. In the main method, two instances of these classes are created and submitted to an ExecutorService to run in separate threads. The get() method is used to wait for the completion of these tasks and retrieve their results.

Let's analyze the code line by line:

java
ExecutorService es = Executors.newFixedThreadPool(2);

This line creates an ExecutorService with a thread pool of 2 threads.

java
Future f1 = es.submit(new Caller("Call")); Future f2 = es.submit(new Runner("Run"));

This creates two Future objects, f1 and f2, by submitting instances of Caller and Runner classes to the ExecutorService.

java
String str1 = (String) f1.get();

This line calls the get() method of f1 to wait for the completion of the Callable task represented by f1, which is an instance of the Caller class. The get() method blocks until the task completes and returns the result. Since the call() method of Caller returns a concatenated string "CallCaller", str1 will be assigned the value "CallCaller".

java
String str2 = (String) f2.get(); //line n1

This line calls the get() method of f2 to wait for the completion of the Runnable task represented by f2, which is an instance of the Runner class. However, the run() method of Runner does not return anything, so f2.get() returns null and the code will block on this line until the Runner task completes.

java
System.out.println(str1 + ":" + str2);

This line prints the concatenated string of str1 and str2, which is "CallCaller:null". Since the Runner task has not completed yet, str2 still holds a null value.

Therefore, the answer is (A) "The program prints: Run Runner Call Caller : null And the program does not terminate."