How to Use Fork/Join Framework in Java


In this example we will show the usage of  the fork/join framework.

Source Code

package com.beginner.examples;

import java.util.concurrent.*;

public class ForkJoinExample extends RecursiveTask{

	private static final int THRESHOLD = 3;

    private int start;
    private int end;

    public ForkJoinExample(int start,int end){
        this.start = start;
        this.end = end;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException{
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinExample example = new ForkJoinExample(2, 7);
        Future result = pool.submit(example);
        System.out.println(result.get());         
        
    }
    
    @Override
    protected Integer compute() {
        int sum = 0;
        // If task is smaller than threshold,direct compute.
        if((end - start) <= THRESHOLD)
        {
            for(int i = start;i <= end;i++)
            {
                sum += i;
            }
        }
        else
        {
            int middle = (start + end) / 2;
            ForkJoinExample fork1 = new ForkJoinExample(start, middle);
            ForkJoinExample fork2 = new ForkJoinExample(middle + 1, end);
            //perform sub-tasks
            fork1.fork();
            fork2.fork();
            //获取子任务结果
            int result1 = fork1.join();
            int result2 = fork2.join();
            sum = result1 + result2;
        }
        return sum;
    }
}

Output:

27
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments