Concurrency
concurrency5ForkJoinDemo
- Path
- pkg7concurrency/concurrency5ForkJoinDemo.java
- Package
- pkg7concurrency
- Study order
- 5
- Run
- Single-file source launch
- Command
- java pkg7concurrency/concurrency5ForkJoinDemo.java
There is no in-browser runner. This is the file from the curriculum, unchanged.
1package pkg7concurrency;2 3/*4 * concurrency5ForkJoinDemo.java5 * -----------------6 * The Fork/Join framework (Java 7) for divide-and-conquer parallelism using a7 * work-stealing pool. RecursiveTask returns a result; RecursiveAction doesn't.8 *9 * IDEA: split the problem (fork), solve subparts in parallel, combine (join).10 * Threshold avoids over-splitting tiny chunks (overhead > benefit).11 */12import java.util.concurrent.*;13 14public class concurrency5ForkJoinDemo {15 16 static class SumTask extends RecursiveTask<Long> {17 private static final int THRESHOLD = 10_000;18 private final long[] arr;19 private final int lo, hi;20 21 SumTask(long[] arr, int lo, int hi) { this.arr = arr; this.lo = lo; this.hi = hi; }22 23 @Override protected Long compute() {24 if (hi - lo <= THRESHOLD) { // small enough: compute directly25 long sum = 0;26 for (int i = lo; i < hi; i++) sum += arr[i];27 return sum;28 }29 int mid = (lo + hi) >>> 1;30 SumTask left = new SumTask(arr, lo, mid);31 SumTask right = new SumTask(arr, mid, hi);32 left.fork(); // run left asynchronously33 long rightResult = right.compute(); // compute right on this thread34 long leftResult = left.join(); // wait for left35 return leftResult + rightResult;36 }37 }38 39 public static void main(String[] args) {40 long[] data = new long[1_000_000];41 for (int i = 0; i < data.length; i++) data[i] = i + 1; // 1..1,000,00042 43 ForkJoinPool pool = ForkJoinPool.commonPool();44 long parallelSum = pool.invoke(new SumTask(data, 0, data.length));45 46 long expected = (long) data.length * (data.length + 1) / 2; // n(n+1)/247 System.out.println("parallelism: " + pool.getParallelism());48 System.out.println("fork/join sum = " + parallelSum);49 System.out.println("expected = " + expected);50 System.out.println("match: " + (parallelSum == expected));51 }52}