Java fork/join 框架說明示例
阿新 • • 發佈:2019-01-22
fork/join 框架設計為將並行任務遞迴拆分為較小的任務, 然後將每個子專案的結果合併以產生總體結果。它是 ExecutorService 介面的一個實現, 它將這些子任務分配給執行緒池中的工作執行緒, 稱為 ForkJoinPool。讓我們開始探索如何定義任務和子任務。
需要繼承RecursiveTask這個類,並實現唯一的一個抽象方法
protected Long compute() {
return null;
}
此方法定義了將手頭的任務拆分為子任務的邏輯和演算法, 以便在不再可能或不方便地進一步劃分時, 生成一個單獨的工作項的結果。為此方法的實施經常類似以下虛擬碼:
if (task is small enough or no longer divisible(任務足夠小或不再可分)) {
compute task sequentially(順序計算該任務)
} else {
split task in two subtasks(將任務拆分2個子任務)
call this method recursively possibly further splitting each subtask(遞迴呼叫此方法可能進一步拆分每個子任務)
wait for the completion of all subtasks(等待所有子任務的完成)
combine the results of each subtask(合併每個子任務的結果)
}
用fork/join框架並行求和示例程式碼:
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;
import java.util.function.Function;
import java.util.stream.LongStream;
@SuppressWarnings("serial")
public class ForkJoinRecursiveTasks extends RecursiveTask<Long>{
public static final ForkJoinPool FORK_JOIN_POOL = new ForkJoinPool();
public static final long THRESHOLD = 10_000;
private final long[] numbers;
private final int start;
private final int end;
private ForkJoinRecursiveTasks(long[] numbers, int start, int end) {
this.numbers = numbers;
this.start = start;
this.end = end;
}
@Override
protected Long compute() {
int length = end - start;
if (length <= THRESHOLD) {
return computeSequentially();
}
ForkJoinRecursiveTasks leftTask = new ForkJoinRecursiveTasks(numbers, start, start + length/2);
leftTask.fork();
ForkJoinRecursiveTasks rightTask = new ForkJoinRecursiveTasks(numbers, start + length/2, end);
Long rightResult = rightTask.compute();
Long leftResult = leftTask.join();
return leftResult + rightResult;
}
private Long computeSequentially() {
long sum = 0;
for (int i = start; i < end; i++) {
sum += numbers[i];
}
return sum;
}
public static long forkJoinSum(long n) {
long[] numbers = LongStream.rangeClosed(1, n).toArray();
ForkJoinTask<Long> task = new ForkJoinSumCalculator(numbers);
return FORK_JOIN_POOL.invoke(task);
}
public static <T, R> long measurePerf(Function<T, R> f, T input) {
long fastest = Long.MAX_VALUE;
for (int i = 0; i < 10; i++) {
long start = System.nanoTime();
R result = f.apply(input);
long duration = (System.nanoTime() - start) / 1_000_000;
System.out.println("Result: " + result);
if (duration < fastest) fastest = duration;
}
return fastest;
}
public static void main(String[] args) {
System.out.println("Range forkJoinSum done in: " + measurePerf(ForkJoinRecursiveTasks::forkJoinSum, 100_000_000L) + " msecs");
}
}