Skip to content

Instantly share code, notes, and snippets.

@nazarov-yuriy
Last active December 19, 2015 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nazarov-yuriy/5880702 to your computer and use it in GitHub Desktop.
Save nazarov-yuriy/5880702 to your computer and use it in GitHub Desktop.
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import algorithm.Solver;
/**
* @author nazarov
*/
public class ExecutorTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
final ForkJoinPool pool = new ForkJoinPool(4);
final Solver solver = new Solver(0, 200000000);
double start = new Date().getTime()/1000.0;
pool.invoke(solver);
double end = new Date().getTime()/1000.0;
System.out.println(solver.result);
System.out.print("Done in: ");
System.out.print(end-start);
System.out.println(" s");
}
}
1.927317886402193
Done in: 27.70899987220764 s
package algorithm;
import java.util.concurrent.RecursiveAction;
/**
* @author nazarov
*/
public class Solver extends RecursiveAction {
private int _from;
private int _to;
public double result;
public Solver(int from, int to) {
_from = from;
_to = to;
}
@Override
protected void compute() {
if (_to - _from < 1000000) {
result = 0;
for(int i = _from; i < _to; i++)
result += Math.sin(i);
} else {
int mid = _from + (_to-_from) / 2;
Solver s1 = new Solver(_from, mid);
s1.fork();
Solver s2 = new Solver(mid, _to);
s2.compute();
s1.join();
result = s1.result + s2.result;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment