Java SE 8 Programmer II: Callable, ExecutorService, and Future Example

Callable, ExecutorService, and Future Example

Question

Given the code fragment: class CallerThread implements Callable<String>{ String str; public CallerThread(String s) {this.str=s;} public String call() throws Exception { return str.concat("Call"); } } and public static void main (String[] args) throws InterruptedException, ExecutionException { ExecutorService es = Executors.newFixedThreadPool(4);//line n1 Future f1 = es.submit (newCallerThread("Call")); String str = f1.get().toString(); System.out.println(str); } Which statement is true?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

B.

The given code fragment creates a class CallerThread that implements the Callable interface with a type parameter of String. The class has a constructor that takes a String parameter and a call() method that returns the concatenation of the input string and "Call".

In the main() method, an ExecutorService is created using the newFixedThreadPool() method with a fixed thread pool size of 4. Then, a Future object f1 is created by submitting a new instance of CallerThread with the string "Call". The get() method is then called on f1 to obtain the result of the call() method, which is stored in a String variable str. Finally, the str variable is printed to the console.

Since the call() method of CallerThread returns the concatenation of the input string and "Call", the get() method on the Future object will return the string "CallCall". Therefore, the program will print "CallCall" to the console and terminate.

Answer: A. The program prints CallCall and terminates.