Java.util.concurrent.RecursiveAction class in Java with Examples
The java.util.concurrent.RecursiveAction
class in Java is a subclass of ForkJoinTask
that represents a task that does not return any result but instead performs some action. It is designed to be used in conjunction with the ForkJoinPool
to execute tasks in parallel.
The RecursiveAction
class provides a compute()
method that must be implemented by the subclass. This method defines the action that the task will perform. The compute()
method can be recursive, allowing the task to be split into smaller subtasks that can be executed in parallel.
Here is an example of how to use the RecursiveAction
class:
import java.util.concurrent.RecursiveAction;
public class MyRecursiveAction extends RecursiveAction {
private int start;
private int end;
public MyRecursiveAction(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected void compute() {
if (end - start <= 10) {
// perform some action on the data
for (int i = start; i < end; i++) {
System.out.println("Processing item " + i);
}
} else {
// split the task into smaller subtasks
int mid = (start + end) / 2;
MyRecursiveAction left = new MyRecursiveAction(start, mid);
MyRecursiveAction right = new MyRecursiveAction(mid, end);
invokeAll(left, right);
}
}
}
In this example, the MyRecursiveAction
class extends RecursiveAction
and overrides the compute()
method. The compute()
method checks if the range of data to be processed is small enough to be handled by a single thread. If it is, the method performs some action on the data. If not, the method splits the task into two smaller subtasks and invokes them in parallel using the invokeAll()
method.
Here is an example of how to use the MyRecursiveAction
class:
import java.util.concurrent.ForkJoinPool;
public class Main {
public static void main(String[] args) {
int[] data = new int[100];
for (int i = 0; i < data.length; i++) {
data[i] = i;
}
MyRecursiveAction task = new MyRecursiveAction(0, data.length);
ForkJoinPool pool = new ForkJoinPool();
pool.invoke(task);
}
}
In this example, an array of data is created and initialized with values. An instance of the MyRecursiveAction
class is created with the range of data to be processed. A ForkJoinPool
is created and the task is invoked using the invoke()
method. The ForkJoinPool
automatically splits the task into smaller subtasks and executes them in parallel.