Java OCA OCP Practice Question 1975

Question

What is the output of the following application?.

package mypkg; // w  w w  .  j  a va 2s .  co  m
import java.util.*; 
import java.util.concurrent.*; 
public class Main { 
   static ExecutorService service = Executors.newFixedThreadPool(8); 
   public static int sleep() { 
      try { 
         Thread.sleep(1000); 
      } catch (Exception e) {} 
      return 1; 
   } 
   public static void hare() { 
      try { 
         Callable c = () -> sleep(); 
         final Collection<Callable<Integer>> r = Arrays.asList(c,c,c); 
         List<Future<Integer>> results = service.invokeAll(r); 
         System.out.println("Hare won the race!"); 
      } catch (Exception e) {e.printStackTrace();} 
   } 
   public static void tortoise() { 
      try { 
         Callable c = () -> sleep(); 
         final Collection<Callable<Integer>> r = Arrays.asList(c,c,c); 
         Integer result = service.invokeAny(r); 
         System.out.println("Tortoise won the race!"); 
      } catch (Exception e) {e.printStackTrace();} 
   } 
   public static void main(String[] p) throws Exception { 
      service.execute(() -> hare()); 
      service.execute(() -> tortoise()); 
   } 
} 
  • A. Hare won the race! is printed first.
  • B. Tortoise won the race! is printed first.
  • C. The code does not compile.
  • D. The result is unknown until runtime.


D.

Note

The code compiles and runs without issue.

The two methods hare() and tortoise() are nearly identical, with one calling invokeAll() and the other calling invokeAny().

The key is to know that both methods operate synchronously, waiting for a result from one or more tasks.

Calling the invokeAll() method causes the current thread to wait until all tasks are finished.

Since each task is one second long and they are being executed in parallel, the hare() method will take about one second to complete.

The invokeAny() method will cause the current thread to wait until at least one task is complete.

Although the result of the first finished thread is often returned, it is not guaranteed.

Since each task takes one second to complete, though, the shortest amount of time this method will return is after one second.

In this regard, the tortoise() method will also take about one second to complete.

Since both methods take about the same amount of time, either may finish first, causing the output to vary at runtime and making Option D the correct answer.

Note that after this program prints the two strings, it does not terminate, since the ExecutorService is not shut down.




PreviousNext

Related