Rollerball
Rollerball

Reputation: 13108

About fork-join framework

Being the method fork(); within compute() how come that does not get called another degree of parallelism each time the method compute() occurs? Is there a boolean flag perhaps? EDIT:

overriding the method compute() of the class RecursiveTask: (pseudocode)

if {array.length<100)
do it
else
divide array by 2;
fork();
int righta = rightArray.compute();
int lefta =(Integer)leftArray.join();
return righta +lefta;

So basically this is the compute() method which gets called recursively and when fork() happens it makes it possible to use parallelism and process that task with another core. However being recursive fork() should be called all the times the method gets recursively called. So in the reality it does not happen (there would be no sense). Is it due to a boolean flag that says fork has already been activated?

Thanks in advance.

Upvotes: 0

Views: 410

Answers (1)

John Vint
John Vint

Reputation: 40256

Look at the API

 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();
   }
 }

Each time compute() is called it will place another computation on another thread (or queue) via fork. compute continuously forks until there are no more n available to process. At this point compute will wait until the "right" side finishes while f1.join() waits for the "left" side to finish.

Whenever join is invoked it will actually make the joining thread execute lower level tasks (lower on the binary tree) giving you the parallelism you want

Upvotes: 2

Related Questions