0

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?

vishal
  • 62
  • 7
  • 2
    Side note: read https://stackoverflow.com/questions/504103/how-do-i-write-a-correct-micro-benchmark-in-java ... the way you are collecting your numbers is *dubious*, at best. – GhostCat Aug 21 '19 at 09:01
  • Isn't the stopwatch benchmarking appropriate here? And keeping the timing aside too my main objective is to understand the difference between the two? – vishal Aug 21 '19 at 09:42
  • 1
    @user3215150 It's fine, but you need to read the answers in the provided link to learn of the many ways in which a benchmarking test can become a complete lie. At least the accepted answer is a must-read. – Gimby Aug 21 '19 at 10:10
  • 1
    I understood his comment wrong. Sorry!! Anyway ,Thanks for the link @GhostCat – vishal Aug 21 '19 at 10:55

0 Answers0