import java.util.concurrent.ForkJoinPool; import java.util.concurrent.RecursiveTask; public class SumCalculatorWithForkJoin { static class SumTask extends RecursiveTask { private final int start; private final int end; private static final int THRESHOLD = 10; SumTask(int start, int end) { this.start = start; this.end = end; } @Override protected Integer compute() { if ((end - start) <= THRESHOLD) { return calculateSum(start, end); } else { int mid = start + (end - start) / 2; SumTask left = new SumTask(start, mid); SumTask right = new SumTask(mid + 1, end); left.fork(); // Asynchronously execute the left subtask return right.compute() + left.join(); // Compute right subtask and wait for the left subtask } } private int calculateSum(int start, int end) { int sum = 0; for (int i = start; i <= end; i++) { sum += i; } return sum; } } public static void main(String[] args) { ForkJoinPool pool = new ForkJoinPool(); int n = 100; // Sum of first 100 integers int totalSum = pool.invoke(new SumTask(1, n)); System.out.println("Total sum of first " + n + " integers: " + totalSum); pool.shutdown(); } }