Java OCA OCP Practice Question 1991

Question

How many times does the following application print 1 at runtime?.

package mypkg; //from   www. j a  v a 2 s  . co m
import java.util.concurrent.*; 
import java.util.stream.*; 
public class Main { 
   private void waitTillFinished(CyclicBarrier c) { 
      try { 
         c.await(); 
         System.out.print("1"); 
      } catch (Exception e) {} 
   } 
   public void row(ExecutorService service) { 
      final CyclicBarrier cb = new CyclicBarrier(5); 
      IntStream.iterate(1, i-> i+1) 
         .limit(12) 
         .forEach(i -> service.submit(() -> waitTillFinished(cb))); 
   } 
   public static void main(String[] oars) { 
      ExecutorService service = null; 
      try { 
         service = Executors.newCachedThreadPool(); 
         new Main().row(service); 
      } finally { 
         service.isShutdown(); 
      } 
   } 
} 
  • A. 0
  • B. 10
  • C. 12
  • D. None of the above


B.

Note

When a CyclicBarrier goes over its limit, the barrier count is reset to zero.

The application defines a CyclicBarrier with a barrier limit of 5 threads.

The application then submits 12 tasks to a cached executor service.

In this scenario, a cached thread executor will use between 5 and 12 threads, reusing existing threads as they become available.

In this manner, there is no worry about running out of available threads.

The barrier will then trigger twice, printing five 1s for each of the sets of threads, for a total of ten 1s.

For this reason, Option B is the correct answer.

The application then hangs indefinitely, as discussed in the next question.




PreviousNext

Related