OCP Question 22, Explanation

Given the code fragment:

class GirlFriend implements Callable<String> {
    String str;
    public GirlFriend(String str) {this.str = str;}
    public String call() throws Exception {
        return str.concat(" Call her!");
    }
}

and

public static void main (String[] args) throws InterruptedException, ExecutionException {
    ExecutorService exec = Executors.newFixedThreadPool(3); //line n1
    Future fut = exec.submit(new GirlFriend("Call her!"));
    String str = fut.get().toString();
    System.out.println(str);
}

Which statement is true?

A. The program prints Call her! Call her! and terminates.
B. The program prints Call her! Call her! and does not terminate.
C. A compilation error occurs at line n1.
D. An ExecutionException is thrown at run time.

 

The correct answer is B.

First off, an ExecutionException gets thrown only when a task has already been aborted due to an exception, so we can’t even see it because main() doesn’t catch anything, and the JVM would stop executing the code right after the first exception.

Secondly, option A is also out immediately because exec wasn’t shut down at all. Let’s make it a rule for our exam:

as soon as you encounter an ExecutorService object,

see if someone calls shutdown() on it,

otherwise the program will run for as long as the JVM itself is running, which helps eliminate options (ref.to Problem 6).

So what’s left is just options B and C, and C is out because there’s nothing wrong with line n1: Executors.newFixedThreadPool() is entirely proper way of creating a pool of threads (whose number is fixed to three in our case).

On a side note please observe that the Future object is raw-typed, that’s why we need to call toString() on the object retrieved by get(). I must confess that I don’t like the way the exam creators code their questions: IMO, data types should be parameterized as much as possible; after all, that’s what generics are all about…

Okay, time for an ambush. Is Callable a functional interface? What interface does it resemble? And what’s the difference between them? Please at least try to answer first and only then click the link to take a look at the javadoc for Callable. It is interesting to note that it took eight years to add such a handy interface to Java (1.5 – codename Tiger – was released back in 2004)…

Leave Comment

Your email address will not be published. Required fields are marked *