Parallel Recursive Task Execution in Java with ForkJoinPool
Java Multithreading: Exercise-14 with Solution
Write a Java program to demonstrate the usage of the ForkJoinPool class for parallel execution of recursive tasks.
Sample Solution:
Java Code:
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class ForkJoinPoolExercise {
public static void main(String[] args) {
int[] array = {
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
};
ForkJoinPool forkJoinPool = new ForkJoinPool();
int sum = forkJoinPool.invoke(new SumTask(array, 0, array.length));
System.out.println("Sum: " + sum);
}
static class SumTask extends RecursiveTask < Integer > {
private final int[] array;
private final int start;
private final int end;
public SumTask(int[] array, int start, int end) {
this.array = array;
this.start = start;
this.end = end;
}
@Override
protected Integer compute() {
if (end - start <= 2) {
int sum = 0;
for (int i = start; i < end; i++) {
sum += array[i];
}
return sum;
} else {
int mid = start + (end - start) / 2;
SumTask leftTask = new SumTask(array, start, mid);
SumTask rightTask = new SumTask(array, mid, end);
invokeAll(leftTask, rightTask);
return leftTask.join() + rightTask.join();
}
}
}
}
Sample Output:
Sum: 55
Explanation:
In the above exercise -
- "SumTask" is a subclass of RecursiveTask<Integer>, where Integer is the result type. It takes an array, a start index, and an end index as input parameters.
- In the compute() method, if the subarray size is small enough (in this case, 2 or fewer elements), it is possible to compute directly the sum of the subarray and return the result.
- Otherwise, we split the subarray into two halves and created two new SumTask instances for each half. We then use the invokeAll() method to submit both tasks to the ForkJoinPool for parallel execution. Finally, we return the sum of the results of both tasks using the join() method.
- The invoke() method is used to start the computation and retrieve the result. In this case, we store the sum in the sum variable and print it.
- When we run this program, the sum of the array elements is computed in parallel using the ForkJoinPool.
Flowchart:
Java Code Editor:
Improve this sample solution and post your code through Disqus
Previous: Java Scheduled Task Execution with ScheduledExecutorService.
Next: Concurrent Read-Write Optimization in Java with StampedLock.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/java-exercises/multithreading/java-multithreading-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics