Java OCA OCP Practice Question 1997

Question

Which statement about the following application is true?.

package mypkg; /*from  ww  w  . java  2s  . c o m*/

import java.util.concurrent.*; 

public class Main extends RecursiveTask<Integer> { 
   final int value; 
   public Main(int value) { 
      this.value = value; 
   } 
   @Override protected Integer compute() {  // w1 
      if(value<1) { 
         return 1; 
      } 
      final Main f1 = new Main(value-1); 
      final Main f2 = new Main(value-2); 
      return f1.compute() * f2.compute(); 
   } 
   public static void main(String... data) { 
      ForkJoinPool pool = new ForkJoinPool(); 
      try { 
         System.out.print(pool.invoke(new Main(10))); 
      } finally { 
         pool.shutdown(); 
      } 
   } 
} 
  • A. The class does not compile due to line w1.
  • B. The class does not compile for another reason.
  • C. The application compiles and uses the fork/join framework correctly.
  • D. The application compiles but does not use the fork/join framework correctly.


D.

Note

The class compiles and runs without issue, making Options A and B incorrect.

The purpose of the fork/join framework is to use parallel processing to complete subtasks across multiple threads concurrently.

Calling the compute() method inside of an existing compute() does not spawn a new thread.

The result is that this task is completed using a single thread, despite a pool of threads being available.

For this reason, Option D is the correct answer.

In order to properly implement the fork/join framework, the compute() method would need to be rewritten.

The f1.compute() call should be replaced with f1.fork() to spawn a separate task, followed by f2.compute() to process the data on the current thread, and ending in f1.join() to retrieve the results of the first task completed while f2.compute() was being processed.

If the code was rewritten as described, then Option C would be the correct answer.




PreviousNext

Related