I am new to ForkJoin Framework in java and finding it a little hard to understand. Here's little piece of code I tried to understand it a bit -:
class RandomTask extends RecursiveAction{
int length;
RandomTask(int n){
length=n;
}
@Override
protected void compute() {
if(length<=100)
{
for(int i=0;i<length; i++)
System.out.println(Thread.currentThread().getName()+" "+i); return;
}
int len1 = length/2, len2=length-len1;
RandomTask randomTask = new RandomTask(len1);
randomTask.fork();
RandomTask randomTask2 = new RandomTask(len2);
randomTask2.compute();
randomTask.join();
}
}
public class ForkJoinTest2 {
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool();
int n = 1000000000;
RandomTask createRandom = new RandomTask(n);
long time = System.currentTimeMillis();
pool.invoke(createRandom);;
System.out.println(System.currentTimeMillis()-time);
}
}
If I replaces randomTask2.compute()
with randomTask2.fork();randomTask2.join();
, It's generally taking more time. For ex - this one shows me the latter taking at least 200 ms more than the former. What's the difference in two?