This technology is based in splitting a task recursively until it is small enough to be performed. The sub-tasks will be executed in parallel in different threads. When the sub-tasks have finished, then a join is invoked to merge the results into one.
Example. The following example is very simple. It consists on a function that calculates consecutive natural numbers in an interval. The class will receive two parameters (number min. and max.). If this interval is greater than 6 (in the example) the task will be split into two sub-tasks.
The class extends RecursiveTask<Long> and implements method compute(). As our class is a task it will be invoked by ForkJoinPool
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.concurrent.ForkJoinPool; | |
import java.util.concurrent.RecursiveTask; | |
class NewTask extends RecursiveTask<Long> { | |
private static final long serialVersionUID = 1895156518961346797L; | |
static final int MAX = 6; | |
int min; | |
int max; | |
NewTask(int min, int max) { | |
this.min = min; | |
this.max = max; | |
} | |
protected Long compute() { | |
if(max - min <= MAX) { | |
System.out.println("Computing"); | |
long result = 0; | |
for(int i=min; i <= max; ++i) | |
result += i; | |
System.out.println("Result1: "+ result); | |
return result; | |
} else { | |
System.out.println("Splitting task"); | |
int mid = min + (max - min) / 2; | |
NewTask left = new NewTask(min, mid); | |
NewTask right = new NewTask(mid+1, max); | |
left.fork(); | |
right.fork(); | |
long sumLeft = left.join(); | |
long sumRight = right.join(); | |
long result = sumRight + sumLeft; | |
System.out.println("Result2: "+ result); | |
return result; | |
} | |
} | |
public static void main (String args[]){ | |
ForkJoinPool.commonPool().invoke(new NewTask(0,12)); | |
} | |
} |
Output console:
Splitting task
Computing
Result1: 21
Computing
Result1: 57
Result2: 78