Skip to content

Instantly share code, notes, and snippets.

@fmamud
Last active August 29, 2015 14:24
Show Gist options
  • Save fmamud/8540d541c1bfeb28c85d to your computer and use it in GitHub Desktop.
Save fmamud/8540d541c1bfeb28c85d to your computer and use it in GitHub Desktop.
package forkjoin;
import java.util.concurrent.RecursiveTask;
public class FibonacciTask extends RecursiveTask<Long> {
/**
*
*/
private static final long serialVersionUID = 8826018716775533826L;
private final int THRESOULD = 5;
private FibonacciProblem problem;
private long result;
public FibonacciTask(FibonacciProblem problem) {
this.problem = problem;
}
protected Long compute() {
if (problem.getN() < THRESOULD) {
result = problem.solve();
} else {
FibonacciTask worker1 = new FibonacciTask(new FibonacciProblem(problem.getN() - 1));
worker1.fork();
FibonacciTask worker2 = new FibonacciTask(new FibonacciProblem(problem.getN() - 2));
worker2.fork();
result = worker2.join() + worker1.join();
}
return result;
}
public long getResult() {
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment