What is the likely result?

Given:
<code>
class Fibonacci extends RecursiveTask<Integer> {
final int n;
Fibonacci (int n) { this.n = n }
Integer compute () {
if (n <= 1)
return n;
Fibonacci f1 = new Fibonacci (n – 1);
f1.fork;
Fibonacci f2 = new Fibonacci (n – 2);
return f2.compute() + f1.join; // Line **
}
Assume that line ** is replaced with:
return f1.join() + f2.compute(); // Line **
</code>
What is the likely result?

Given:

class Fibonacci extends RecursiveTask<Integer> {
final int n;
Fibonacci (int n) { this.n = n }
Integer compute () {
if (n <= 1)
return n;
Fibonacci f1 = new Fibonacci (n – 1);
f1.fork;
Fibonacci f2 = new Fibonacci (n – 2);
return f2.compute() + f1.join; // Line **
}
Assume that line ** is replaced with:
return f1.join() + f2.compute(); // Line **

What is the likely result?

A.
The program produces the correct result, with similar performance to the original.

B.
The program produces the correct result, with performance degraded to the equivalent of being
single-threaded.

C.
The program produces an incorrect result.

D.
The program goes into an infinite loop.

E.
An exception is thrown at runtime.

F.
The program produces the correct result, with better performance than the original.

Explanation:
Changing the code is not useful. In the original code (return f2.compute() + f1.join; )
f1 and f2 are run in parallel. The result is joined.
With the changed code (return f1.join() + f2.compute();) f1 is first executed and finished, then is f2
executed.
Note 1:The join method allows one thread to wait for the completion of another.
If t is a Thread object whose thread is currently executing,
t.join();
causes the current thread to pause execution until t’s thread terminates.
Note 2:New in the Java SE 7 release, the fork/join framework is an implementation of the
ExecutorService interface that helps you take advantage of multiple processors. It is designed for
work that can be broken into smaller pieces recursively. The goal is to use all the available
processing power to enhance the performance of your application.
As with any ExecutorService, the fork/join framework distributes tasks to worker threads in a
thread pool. The fork/join framework is distinct because it uses a work-stealing algorithm. Worker
threads that run out of things to do can steal tasks from other threads that are still busy.
Reference: The Java Tutorials,Joins,Fork/Join



Leave a Reply 0

Your email address will not be published. Required fields are marked *