Created
November 19, 2015 14:17
-
-
Save TheDIM47/11b8438b5522c406700a to your computer and use it in GitHub Desktop.
ForkJoin sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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