Why is this Java code with Join/Fork framework to calculate Fibonacci numbers so slow?

200 views Asked by At

What is wrong about this code ? I am using Fork/Join Framework to make use of parallel Threads. But to calculate Fibonacci takes much longer than normal calculation with just 1 thread.

public class FibonacciRecursiveTask extends RecursiveTask<Integer> {

    public static final int THRESHOLD = 1;

    int n ;

    public FibonacciRecursiveTask(int n)
    {
        this.n = n;
    }

    @Override
    protected Integer compute() {

        if(n<= THRESHOLD)
        {
            //System.out.println(n);
            return n;
        }

        FibonacciRecursiveTask left = new FibonacciRecursiveTask(n-1);
        left.fork();
        FibonacciRecursiveTask right = new FibonacciRecursiveTask(n-2);
        Integer res1 = right.compute();
        Integer res2 = left.join();
        return res1 + res2;
    }
}

class RecursiveTaskDemo
{
    public static void main(String[] args)
    {
        FibonacciRecursiveTask task = new FibonacciRecursiveTask(44);
        ForkJoinPool pool = new ForkJoinPool(8);
        Integer res = pool.invoke(task);
        System.out.println(res);
    }
}

This is normal sequential with just 1 thread. This is like 4 times faster.

class Fib
{
    public static void main(String[] args)
    {
        System.out.println(fib(44));
    }

    public static int fib(int n)
    {
        if(n <= 1)
        {
            return n;
        }
        return fib(n-2) + fib(n-1);
    }
}
0

There are 0 answers