Last active
October 16, 2024 12:41
-
-
Save ajiniesta/5081563 to your computer and use it in GitHub Desktop.
Fibonacci with ForkJoinPool.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import java.util.concurrent.ForkJoinPool; | |
| import java.util.concurrent.RecursiveTask; | |
| public class FibonacciTest { | |
| /** | |
| * @param args | |
| */ | |
| public static void main(String[] args) { | |
| Long n = 20L; | |
| Long res; | |
| long t1 = System.currentTimeMillis(); | |
| res = fibonacci(n); | |
| long t2 = System.currentTimeMillis(); | |
| System.out.println("Time in sequential = " + (t2- t1)+" ms. Result: " + res); | |
| { | |
| t1 = System.currentTimeMillis(); | |
| ForkJoinPool pool = new ForkJoinPool(); | |
| Fibonacci fb = new Fibonacci(n); | |
| pool.invoke(fb); | |
| res = fb.getRawResult(); | |
| t2 = System.currentTimeMillis(); | |
| System.out.println("Time in fork join= " + (t2- t1)+" ms. Result: " + res); | |
| } | |
| { | |
| int processors = Runtime.getRuntime().availableProcessors(); | |
| t1 = System.currentTimeMillis(); | |
| // processors *= 100; | |
| ForkJoinPool pool = new ForkJoinPool(processors); | |
| Fibonacci fb = new Fibonacci(n); | |
| pool.invoke(fb); | |
| res = fb.getRawResult(); | |
| t2 = System.currentTimeMillis(); | |
| System.out.println("Time in fork join= " + (t2- t1)+" ms. In "+processors+ " processor. Result: " + res); | |
| } | |
| } | |
| @SuppressWarnings("serial") | |
| static class Fibonacci extends RecursiveTask<Long> { | |
| final Long n; | |
| Fibonacci(Long n) { this.n = n; } | |
| public Long compute() { | |
| if (n <= 1) | |
| return n; | |
| Fibonacci f1 = new Fibonacci(n - 1); | |
| f1.fork(); | |
| Fibonacci f2 = new Fibonacci(n - 2); | |
| return f2.compute() + f1.join(); | |
| } | |
| } | |
| private static Long fibonacci(Long n){ | |
| if (n <= 1){ | |
| return n; | |
| }else{ | |
| return fibonacci(n-2) + fibonacci(n-1); | |
| } | |
| } | |
| } |
Author
I ran this test. I thought fork-join-pool would have better performance, but Sequential always ran faster.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Full working example extracted from the example shown in the api of RecursiveTask: http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/RecursiveTask.html