This is a program for Fibonacci using Java 7 ForkJoin . But seems like there is a dead lock.
package ForkJoin;
import java.time.LocalTime;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import static java.time.temporal.ChronoUnit.MILLIS;
class Fibonacci extends RecursiveTask<Integer>{
int num;
Fibonacci(int n){
num = n;
}
@Override
protected Integer compute() {
if(num <= 1)
return num;
Fibonacci fib1 = new Fibonacci(num-1);
fib1.fork();
Fibonacci fib2 = new Fibonacci(num-2);
fib2.fork();
return fib1.join()+ fib2.join();
}
}
public class ForkJoinFibonaaciEx {
public static void main(String[] arg){
LocalTime before = LocalTime.now();
int processors = Runtime.getRuntime().availableProcessors();
System.out.println("Available core: "+processors);
ForkJoinPool pool = new ForkJoinPool(processors);
System.out.println("Inside ForkJoin for number 50: "+pool.invoke(new Fibonacci(50)));
LocalTime after = LocalTime.now();
System.out.println("Total time taken: "+MILLIS.between(before, after));
}
}
JVisualVM ---- shows there is dead lock. Not sure what the real issue is.
Also, I have noticed codes where developers have done fork call for one portion and compute for other half of the problem.
e.g. here in this example they use fib1.fork() and fib2 they don't fork.
You can see the full example https://github.com/headius/forkjoin.rb/blob/master/examples/recursive/Fibonacci.java
Your help is very much appreciated. Thank you and have a great With regards Deenadayal Manikanta