Java OCA OCP Practice Question 1981

Question

What is the output of the following application?.

package mypkg; /*from   w w  w. j  a  v  a  2 s . c  o m*/
import java.util.concurrent.*; 
public class Main extends RecursiveAction { 
   static int[] sheep = new int[] {1,2,3,4}; 
   final int start; 
   final int end; 
   int count = 0; 
   public Main(int start, int end) { 
      this.start = start; 
      this.end = end; 
   } 
   public void compute() { 
      if(end-start<2) { 
         count+=sheep[start]; 
         return; 
      } else { 
         int middle = start + (end-start)/2; 
         invokeAll(new Main(start,middle), 
               new Main(middle,end)); 
      } 
   } 
   public static void main(String[] night) { 
      ForkJoinPool pool = new ForkJoinPool(); 
      Main action = new Main(0,sheep.length); 
      pool.invoke(action); 
      pool.shutdown(); 
      System.out.print(action.count); 
   } 
} 
  • A. 0
  • B. 10
  • C. The code does not compile.
  • D. None of the above.


A.

Note

The code compiles, so Option C is incorrect.

The application attempts to count the elements of the sheep array, recursively.

For example, the first two elements are totaled by one thread and added to the sum of the remainder of the elements in the array, which is calculated by another thread.

The count value is not marked static and not shared by all of the Main subtasks.

The value of count printed in the main() menu comes from the first Main instance, which does not modify the count variable.

The application prints 0, and Option A is the correct answer.

If count was marked static, then the application would sum the elements correctly, printing 10, and Option B would be the correct answer.




PreviousNext

Related