Java OCA OCP Practice Question 2198

Question

What is the output of the following application?.

package mypkg; /*  w w w  .j a va  2s . co  m*/
import java.util.concurrent.*; 
import java.util.stream.IntStream; 
public class Main { 
   private static void await(CyclicBarrier b) { 
      try { 
         b.await(); 
      } catch (InterruptedException | BrokenBarrierException e) { 
         e.printStackTrace(); 
      } 
   } 
   public static void main(String[] chalk) { 
      ExecutorService s = Executors.newFixedThreadPool(4); 
      final CyclicBarrier b = new CyclicBarrier(4, 
         () -> System.out.print("Main!")); 
      IntStream 
         .iterate(1, q -> 2) 
         .limit(10) 
         .forEach(q -> s.execute(() ->await(b))); 
      s.shutdown(); 
   } 
} 
  • A. Main! is printed and exits.
  • B. Main! is printed twice and exits.
  • C. The code does not compile.
  • D. The output cannot be determined ahead of time.
  • E. The program hangs indefinitely at runtime because the IntStream is not parallel.
  • F. None of the above


F.

Note

The code compiles without issue, making Option C incorrect.

The main() method creates a thread pool of four threads.

It then submits 10 tasks to it.

At any given time, the ExecutorService has up to four threads active, which is the same number of threads required to reach the CyclicBarrier limit.

Therefore, the barrier limit is reached twice, printing Main! twice, making Option A incorrect.

The program does not terminate, so Option B is also incorrect.

While eight of the tasks have been completed, two are left running.

Since no more tasks will call the await() method, the CyclicBarrier limit is never reached, and the two remaining threads' tasks hang indefinitely.

Option F is the correct answer.

Option E is incorrect because making the IntStream parallel would not change the result.

Option D is incorrect because the result is the same no matter how many times the program is executed.




PreviousNext

Related