Java OCA OCP Practice Question 1993

Question

What is the expected output of the following application?.

package mypkg; /*  www.  java  2 s. c  om*/

import java.util.concurrent.*; 
import java.util.stream.*; 

public class Main { 
   static BlockingDeque<Integer> queue = new LinkedBlockingDeque<>(); 
   public static void main(String[] participants) throws Exception { 
      IntStream.iterate(1, i -> i+1).limit(5) 
         .parallel() 
         .forEach(s -> queue.offerLast(s,10000,TimeUnit.MILLISECONDS)); 
      IntStream.iterate(1, i -> 5).limit(10) 
         .parallel() 
         .forEach(s -> queue.pollFirst(10,TimeUnit.SECONDS)); 
      System.out.print(queue.size()); 
   } 
} 
  • A. 0
  • B. A number from 0 to 5
  • C. The code does not compile.
  • D. The code compiles but throws an exception at runtime.


C.

Note

The code does not compile because the blocking methods offerLast() and pollFirst() each throw a checked InterruptedException that are not handled by the lambda expressions, so Option C is the correct answer.

If the lambda expressions were wrapped with try-catch blocks, then the process would first add all items to the queue, then remove them all of them, resulting in an output of 0.

Option A would be the correct answer.

Even though the tasks are completed in parallel, each stream does not terminate until all tasks are done.




PreviousNext

Related