I am playing with RecursiveTask of the concurrent package from Java 7. It says this class has an implementation of forkJoin approach and can split my tasks in different threads. So I used a fibonacci example from the Java doc and compared the execution time with a normal recursive fibonacci. And for my surprise the normal recursive took less time! Why? Am I doing anything wrong?
import java.util.concurrent.RecursiveTask;
public class FibonacciJava extends RecursiveTask<Long> {
private static final long serialVersionUID = -2495228492435217747L;
private long n;
protected long valor;
public FibonacciJava(long n) {
this.n = n;
}
@Override
protected Long compute() {
if (n <= 1) {
return n;
}
FibonacciJava f1 = new FibonacciJava(n - 1);
f1.fork();
FibonacciJava f2 = new FibonacciJava(n - 2);
return f2.compute() + f1.join();
}
public long fibonacci(long valor) {
if (valor <= 1)
return valor;
else {
return fibonacci(valor - 1) + fibonacci(valor - 2);
}
}
public static void main(String[] args) {
long value = 40;
FibonacciJava fibonacciJava = new FibonacciJava(value);
long startTimeMillis = System.currentTimeMillis();
System.out.println("RecursiveTask FibonacciJava: "
+ fibonacciJava.compute() + " in "
+ (System.currentTimeMillis() - startTimeMillis)
+ " miliseconds.");
startTimeMillis = System.currentTimeMillis();
System.out.println("Recursive FibonacciJava: "
+ fibonacciJava.fibonacci(value) + " in "
+ (System.currentTimeMillis() - startTimeMillis)
+ " miliseconds.");
}
}
time:
RecursiveTask FibonacciJava: 102334155 in 3681 miliseconds.
Recursive FibonacciJava: 102334155 in 573 miliseconds.