Fork/Join Framework: General Logic

Introduction

The Fork/Join framework in Java is a powerful tool for parallelizing tasks. It is designed to recursively split tasks into smaller subtasks and process them concurrently, leveraging all available processor cores. Here's the general logic of how it is used.

General Logic

  1. Check Task Size: First, check whether the task is small enough to be performed directly without forking. If it is, perform the task directly.
  2. Split the Task: If the task is too large to handle directly, split it into multiple smaller tasks (at least 2).
  3. Submit Subtasks: Submit the subtasks back to the Fork/Join pool using invokeAll(). The pool manages the execution of these subtasks concurrently.

Example Code

Below is an example of implementing the Fork/Join framework in Java:

import java.util.concurrent.RecursiveTask;
import java.util.concurrent.ForkJoinPool;

public class ForkJoinExample {

    static class SumTask extends RecursiveTask {
        private final int[] numbers;
        private final int start;
        private final int end;
        private static final int THRESHOLD = 10;

        public SumTask(int[] numbers, int start, int end) {
            this.numbers = numbers;
            this.start = start;
            this.end = end;
        }

        @Override
        protected Integer compute() {
            if ((end - start) <= THRESHOLD) {
                int sum = 0;
                for (int i = start; i < end; i++) {
                    sum += numbers[i];
                }
                return sum;
            } else {
                int mid = (start + end) / 2;
                SumTask task1 = new SumTask(numbers, start, mid);
                SumTask task2 = new SumTask(numbers, mid, end);

                invokeAll(task1, task2);

                return task1.join() + task2.join();
            }
        }
    }

    public static void main(String[] args) {
        int[] numbers = new int[100];
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = i + 1;
        }

        ForkJoinPool pool = new ForkJoinPool();
        SumTask task = new SumTask(numbers, 0, numbers.length);
        int result = pool.invoke(task);

        System.out.println("Sum: " + result);
    }
}
        

Conclusion

The Fork/Join framework provides a straightforward way to divide and conquer tasks for efficient parallel execution. By checking task size, splitting tasks, and submitting subtasks back to the pool, you can harness the full power of your CPU cores.

Post a Comment

0 Comments