Wednesday, June 21, 2023

How to use Fork Join in Java Multithreading - Tutorial with Example

Fork-Join is a framework in Java that allows you to perform parallel processing by dividing a task into smaller subtasks and merging the results. It is part of the java.util.concurrent package and is useful for efficiently utilizing multiple CPU cores for concurrent processing. Here's a step-by-step guide on how to use Fork-Join in Java:


Step 1: Create the Fork-Join task


Extend the RecursiveTask class if your task returns a result, or extend the RecursiveAction class if your task does not return a result.

Override the compute() method, which represents the main computation performed by the task.

Break down the task into smaller subtasks and delegate them to other instances of the same task.

Combine the results of the subtasks to obtain the final result (if applicable).


Here's an example of a RecursiveTask that computes the sum of an array of integers:


import java.util.concurrent.RecursiveTask;

public class SumTask extends RecursiveTask {
    private static final int THRESHOLD = 1000;
    private int[] array;
    private int start;
    private 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 <= THRESHOLD) {
            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(); // Start the left subtask asynchronously
            int rightResult = rightTask.compute(); // Compute the right subtask synchronously
            int leftResult = leftTask.join(); // Wait for the left subtask to complete and get its result
            return leftResult + rightResult;
        }
    }
}

Step 2: Create the Fork-Join pool and submit the task 

Create an instance of the ForkJoinPool class, which manages the execution of Fork-Join tasks. 

Create an instance of your Fork-Join task. Submit the task to the Fork-Join pool using the invoke() or submit() method. 


Here's an example of how to use the SumTask in the main method:


import java.util.concurrent.ForkJoinPool;

public class Main {
    public static void main(String[] args) {
        int[] array = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        SumTask task = new SumTask(array, 0, array.length);
        int result = forkJoinPool.invoke(task);

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

In this example, we create a Fork-Join pool, create an instance of SumTask, and then invoke the task using the invoke() method of the pool. 

The result is obtained and printed to the console. By breaking down the task into smaller subtasks and using the Fork-Join framework, you can take advantage of parallel processing and improve the performance of your Java multithreaded applications.

No comments:

Post a Comment