Example Using RecursiveTask
Below is the example using Recursive Task:
Java
import java.util.concurrent.RecursiveTask; @AllArgsConstructor class SumTask extends RecursiveTask<Integer> { private final int [] array; private final int start; private final int end; @Override protected Integer compute() { if (end - start <= 10 ) { int sum = 0 ; for ( int i = start; i < end; i++) { sum += array[i]; } return sum; } else { int mid = (start + end) / 2 ; SumTask leftTask = new SumTask(array, start, mid); SumTask rightTask = new SumTask(array, mid, end); leftTask.fork(); int rightResult = rightTask.compute(); int leftResult = leftTask.join(); return leftResult + rightResult; } } } |
In this example, the `SumTask` class showcases the principles discussed above. It divides the task of summing an array into smaller subtasks, allowing for parallelized computation.
Understanding RecursiveAction
RecursiveAction is similar to RecursiveTask, but it is used for tasks that do not return a result. It also requires you to override the compute() method.
Java
import java.util.concurrent.RecursiveAction; @AllArgsConstructor class PrintTask extends RecursiveAction { private final int [] array; private final int start; private final int end; @Override protected void compute() { if (end - start <= 10 ) { for ( int i = start; i < end; i++) { System.out.print(array[i] + " " ); } System.out.println(); } else { int mid = (start + end) / 2 ; PrintTask leftTask = new PrintTask(array, start, mid); PrintTask rightTask = new PrintTask(array, mid, end); leftTask.fork(); rightTask.compute(); leftTask.join(); } } } |
In this example, the PrintTask class showcases the principles discussed above. It divides the task of printing elements of an array into smaller subtasks, allowing for parallelized execution.
Parallelizing Tasks in Java using ForkJoinPool
In the realm of concurrent programming, Java’s ForkJoinPool stands out as a powerful framework for parallelizing tasks. It is particularly adept at handling computationally intensive applications, leveraging the capabilities of modern multi-core processors. This article will delve into the intricacies of the ForkJoinPool framework, shedding light on its inner workings and exploring its indispensable components: RecursiveTask and RecursiveAction.