Skip to content

Instantly share code, notes, and snippets.

@TheDIM47
Created November 19, 2015 14:17
Show Gist options
  • Save TheDIM47/11b8438b5522c406700a to your computer and use it in GitHub Desktop.
Save TheDIM47/11b8438b5522c406700a to your computer and use it in GitHub Desktop.
ForkJoin sample
package mireyn;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveAction;
public class ForkJoinArrayEvaluator {
private static final int CPU = Runtime.getRuntime().availableProcessors();
public static int THRESHOLD = CPU * 16;
public int[] evaluate(int[] data, int p) throws InterruptedException {
if (data == null) {
throw new IllegalArgumentException("Data must not be null");
}
if (data.length == 0) {
return data;
}
final ForkJoinPool pool = new ForkJoinPool();
pool.invoke(new EvalTask(data, 0, data.length, p));
return data;
}
private static class EvalTask extends RecursiveAction {
EvalTask(int[] data, int start, int stop, int p) {
this.data = data;
this.start = start;
this.stop = stop;
this.p = p;
}
@Override
protected void compute() {
if ((stop - start) <= THRESHOLD) {
for (int i = start; i < stop; i++) {
data[i] = (int) Math.pow(data[i], p); // ExtLib.eval(data[i], p);
}
} else {
final int mid = (start + stop) >>> 1;
ForkJoinTask.invokeAll(
new EvalTask(data, start, mid, p),
new EvalTask(data, mid, stop, p)
);
}
}
private final int[] data;
private final int start;
private final int stop;
private final int p;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment