Commit ce1f11bb authored by Mohamad Bashar Desoki's avatar Mohamad Bashar Desoki

06. Fibonacci Fork/Join

parent 2c4c5e9f
...@@ -13,8 +13,11 @@ ...@@ -13,8 +13,11 @@
### Introduce to ForkJoin Framework ### Introduce to ForkJoin Framework
* ArraySum using Recursive Action * ArraySum using Recursive Action
* Fibonacci Using Recursive Task
### Acknowledgments ### Acknowledgments
Inspiration, code snippets, etc. Inspiration, code snippets, etc.
* [Java - MultiThreading](https://www.youtube.com/watch?v=9DvDheKRJ9Y&t=656s) * [Java - MultiThreading](https://www.youtube.com/watch?v=9DvDheKRJ9Y&t=656s)
* [Java - Executor Service](https://jenkov.com/tutorials/java-util-concurrent/executorservice.html) * [Java - Executor Service](https://jenkov.com/tutorials/java-util-concurrent/executorservice.html)
* [Recursive Task](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/RecursiveTask.html)
* [Parallel Programming in Java] (https://www.coursera.org/learn/parallel-programming-in-java)
\ No newline at end of file
import java.util.concurrent.RecursiveTask;
/*
However, besides being a dumb way to compute Fibonacci functions (there is a simple fast linear algorithm that you'd use in practice),
this is likely to perform poorly because the smallest subtasks are too small to be worthwhile splitting up.
Instead, as is the case for nearly all fork/join applications,
you'd pick some minimum granularity size (for example 10 here) for which you always sequentially solve rather than subdividing.
*/
public class Fibonacci extends RecursiveTask<Integer> {
final int n;
public Fibonacci(int n) { this.n = n; }
public Integer compute() {
if(n > 20) {
if (n <= 1)
return n;
Fibonacci f1 = new Fibonacci(n - 1);
f1.fork();
Fibonacci f2 = new Fibonacci(n - 2);
return f2.compute() + f1.join();
}else{
return computeSeq();
}
}
public Integer computeSeq() {
if (n <= 1)
return n;
Fibonacci f1 = new Fibonacci(n - 1);
Fibonacci f2 = new Fibonacci(n - 2);
return f2.computeSeq() + f1.computeSeq();
}
}
import junit.framework.TestCase;
public class FibonacciTest extends TestCase {
int n=40;
public void testFiboPP(){
long start = System.currentTimeMillis();
Fibonacci fib = new Fibonacci(n);
int res = fib.compute();
long end = System.currentTimeMillis()-start;
System.out.printf("Fibonacci for %d is %d, and parallel execution took %d ms\n",n,res,end);
// Fibonacci parallel takes 144269 fon n = 50 before enhancement 1
}
public void testFiboSeq(){
long start = System.currentTimeMillis();
Fibonacci fib = new Fibonacci(n);
int res = fib.computeSeq();
long end = System.currentTimeMillis()-start;
System.out.printf("Fibonacci for %d is %d, and sequential execution took %d ms\n",n,res,end);
//Fibonacci Sequential takes 86495 fon n = 50 before enhancement 1
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment