Fork in Java
Fork in Java
Key Concepts
1. Fork: Splits a task into smaller subtasks that can run concurrently.
2. Join: Combines the results of the subtasks once they’re complete.
Components
1. ForkJoinPool: A specialized thread pool that manages and executes Fork/Join tasks. It
uses a work-stealing algorithm where idle threads can "steal" tasks from others to
optimize CPU usage.
2. ForkJoinTask: The base class for tasks that can be executed in the Fork/Join framework.
There are two primary subclasses:
o RecursiveTask: Used for tasks that return a result.
o RecursiveAction: Used for tasks that do not return a result.
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;
@Override
protected Long compute() {
if (end - start <= THRESHOLD) {
// Perform computation directly
long sum = 0;
for (int i = start; i < end; i++) {
sum += numbers[i];
}
return sum;
} else {
// Split task into smaller subtasks
int middle = (start + end) / 2;
How It Works
1. Thresholding: If the task size is below the threshold (e.g., 10 numbers), it computes
directly.
2. Splitting: Otherwise, it splits the task into smaller subtasks (left and right halves).
3. Parallel Execution: One subtask is executed in parallel (forked), while the other is
computed in the current thread.
4. Result Aggregation: The results of the subtasks are joined to form the final result.
Benefits