Java OCA OCP Practice Question 2242

Question

Which statement about the following class is correct?

package mypkg; //w w w  .ja va 2s.  c om
import java.util.concurrent.*; 
public class Main extends RecursiveTask<String> {  // j1 
  final int remainder; 
  public Main(int remainder) {  // j2 
     this.remainder = remainder; 
  } 
  @Override 
  protected String compute() { 
     if (remainder <= 1) 
        return "1"; 
     else { 
        Main otherTask = new Main(remainder - 1); 
        String otherValue = otherTask.fork().join();  // j3 
        return otherValue 
           + new Main(remainder - 2).compute(); 
     } 
  } 
  public static void main(String[] purpose) { 
     ForkJoinPool pool = new ForkJoinPool(); 
     ForkJoinTask<?> task = new Main(10); 
      System.out.print(pool.invoke(task)); 
      pool.shutdown(); 
   } 
} 
  • A. The code does not compile due to line j1.
  • B. The code does not compile due to line j2.
  • C. The code does not compile due to line j3.
  • D. The code compiles and properly implements the fork/join framework in a multi-threaded manner.
  • E. The code compiles but does not implement the fork/join framework in a proper multi-threaded manner.
  • F. The class compiles and prints an exception at runtime.


E.

Note

The class compiles, so Options A, B, and C are incorrect.

It also does not produce an exception at runtime, so Option F is incorrect.

The question reduces to whether or not the compute() method properly implements the fork/join framework in a multi-threaded manner.

The compute() method returns "1" in the base case.

In the recursive case, it creates two Main tasks.

In order to use multiple concurrent threads, the first task should be started asynchronously with fork().

While that is processing, the second task should be executed synchronously with compute() with the results combined using the join() method.

That's not what happens in this compute() method though.

The first task is forked and then joined before the second task has even started.

The result is that the current thread waits for the first task to completely finish before starting and completing the second task synchronously.

At runtime, this would result in single-threaded-like behavior.

Since this is a poor implementation of the fork/join framework, Option E is the correct answer.




PreviousNext

Related