package test;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class Runner {
/**
* @param args
* @throws InterruptedException
* @throws ExecutionException
*/
public static void main(String[] args) throws InterruptedException, ExecutionException {
ForkJoinPool pool = new ForkJoinPool();
Task executionTask = new Task(1000000000.0);
pool.invoke(executionTask);
System.out.println(pool.toString());
System.out.println(String.format("Full execution time is %d", executionTask.get()));
pool.shutdown();
}
private static class Task extends RecursiveTask<Long> {
private static final long serialVersionUID = 1L;
private static final int THRESHOLD = 10000;
private double targetNumber;
public Task(double targetNumber) {
this.targetNumber = targetNumber;
}
@Override
protected Long compute() {
if (targetNumber > THRESHOLD) {
double half = targetNumber / 2;
Task firstHalf = new Task(half);
System.out.println(String.format("Fork was created for" +
" %f target number", half));
firstHalf.fork();
Task secondHalf = new Task(targetNumber - half);
return firstHalf.join() + secondHalf.compute();
} else {
return computeDirectly();
}
}
private long computeDirectly() {
long startTime = System.currentTimeMillis();
double goal = targetNumber;
while (goal > 0) {
goal =- 0.01;
}
long executionTime = System.currentTimeMillis() - startTime;
System.out.println(String.format("Fork with %f target executed during %d miliseconds",
targetNumber, executionTime));
return executionTime;
}
}
}