Skip to content

Instantly share code, notes, and snippets.

@ansig
Created January 20, 2015 18:52
Show Gist options
  • Save ansig/d156eedbc1884f6fe6b9 to your computer and use it in GitHub Desktop.
Save ansig/d156eedbc1884f6fe6b9 to your computer and use it in GitHub Desktop.
Solve a computing task with the ForkJoin framework.
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
/**
* Solve a computing task with the ForkJoin framework.
*/
public class MyForkJoinPool {
private static final int NTHREADS = 10;
public static void main(String[] args) {
ForkJoinPool pool = new ForkJoinPool(NTHREADS);
Long sum = pool.invoke(new SumTask(0l, 1000000l));
System.out.printf("Final sum: %d%n", sum);
}
}
class SumTask extends RecursiveTask<Long> {
private static final int THRESHOLD = 10;
private Long from;
private Long to;
public SumTask(Long from, Long to) {
this.from = from;
this.to = to;
}
@Override
public Long compute() {
Long sum = 0l;
if ((to-from) <= THRESHOLD) {
System.out.printf("%s computing directly: %d-%d%n", getName(), from, to);
for (long i = from; i <= to; i++) {
sum += i;
}
} else {
long mid = (from+to)/2;
// fork
System.out.printf("%s forking lower half: %d-%d%n", getName(), from, mid);
SumTask lower = new SumTask(from, mid);
lower.fork();
// compute
System.out.printf("%s computing higher half: %d-%d%n", getName(), mid+1, to);
SumTask higher = new SumTask(mid+1, to);
Long higherRes = higher.compute();
// join
sum = lower.join() + higherRes;
}
System.out.printf("%s returning sum: %d%n", getName(), sum);
return sum;
}
private String getName() {
return Thread.currentThread().getName();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment