Skip to content

Instantly share code, notes, and snippets.

@theboreddev
Created July 12, 2020 21:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save theboreddev/69b38c5352694bd59089f600eb777937 to your computer and use it in GitHub Desktop.
Save theboreddev/69b38c5352694bd59089f600eb777937 to your computer and use it in GitHub Desktop.
ForkJoinTak
package com.theboreddev.examples.forkjoin;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
public class ForkJoinExample {
public static void main(String[] args) {
final int numberOfProcessors = Runtime.getRuntime().availableProcessors();
final ForkJoinPool forkJoinPool = new ForkJoinPool(numberOfProcessors);
final ForkJoinTask<Integer> result = forkJoinPool.submit(new Fibonacci(30));
System.out.println("The result is : " + result.join());
}
static class Fibonacci extends RecursiveTask<Integer> {
private final int number;
public Fibonacci(int number) {
this.number = number;
}
@Override
protected Integer compute() {
if (number <= 1) {
return number;
} else {
Fibonacci fibonacciMinus1 = new Fibonacci(number - 1);
Fibonacci fibonacciMinus2 = new Fibonacci(number - 2);
fibonacciMinus1.fork();
return fibonacciMinus2.compute() + fibonacciMinus1.join();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment