package dev.elaine.concurrency;

import java.util.concurrent.RecursiveTask;

public final class ForkJoinSumSample extends RecursiveTask<Long> {
    private static final int THRESHOLD = 10_000;
    private final long startInclusive;
    private final long endExclusive;

    public ForkJoinSumSample(long startInclusive, long endExclusive) {
        this.startInclusive = startInclusive;
        this.endExclusive = endExclusive;
    }

    @Override
    protected Long compute() {
        if (endExclusive - startInclusive <= THRESHOLD) {
            long total = 0;
            for (long value = startInclusive; value < endExclusive; value++) {
                total += value;
            }
            return total;
        }
        long middle = (startInclusive + endExclusive) >>> 1;
        ForkJoinSumSample left = new ForkJoinSumSample(startInclusive, middle);
        left.fork();
        long rightResult = new ForkJoinSumSample(middle, endExclusive).compute();
        return left.join() + rightResult;
    }

    public static void main(String[] args) {
        long result = java.util.concurrent.ForkJoinPool.commonPool()
                .invoke(new ForkJoinSumSample(1, 1_000_001));
        System.out.println("求和=" + result);
    }
}
