Skip to content
  • Facebook
GeekCer Logo

GeekCer

The geek's Coding education and Review centre

  • Home
  • Tutorials
    • Java
    • Servlet
    • JSP
    • Python
    • C Tutorial
    • Spring
    • Spring Boot
    • MongoDB
    • Hibernate
    • Data Structure
  • General Knowledge
  • Biography
  • Grammar
  • Festival (त्योहार)
  • Interview
  • Differences
  • Important
  • Toggle search form

Home » Java » Fork/Join Framework in Java | RecursiveTask, RecursiveAction

  • Servlet Tutorial
    Servlet Tutorial Servlet
  • Structured Vs Unstructured Data in Hindi | Key Difference
    Structured Vs Unstructured Data in Hindi | Key Difference Differences
  • Chhath Puja Story
    Chhath Puja History : क्यों मनाते हैं छठ महापर्व Festival
  • Kapil Sharma Show, Comedy Show in Hindi
    Kapil Sharma Show, Comedy Show in Hindi Biography
  • Real life Inspirational Stories in Hindi | Success story in Hindi
    Real life Inspirational Stories in Hindi | Success story in Hindi Biography
  • What is Mutual Fund?
    What is Mutual Fund? Important
  • Dynamic memory allocation in C, malloc, realloc, calloc and free
    Dynamic memory allocation in C, malloc, realloc, calloc and free Data Structure
  • Java Hibernate Framework Tutorial
    Java Hibernate Framework Tutorial | Hibernate For Beginners Hibernate

Fork/Join Framework in Java | RecursiveTask, RecursiveAction

Posted on May 11, 2022May 12, 2022 By admin No Comments on Fork/Join Framework in Java | RecursiveTask, RecursiveAction
Fork/Join Framework in Java | RecursiveTask, RecursiveAction

Fork/Join allows us to divide the task into smaller pieces and combine the results. It uses Work-stealing algorithm. If more than one thread is working at the same time, and one thread completes its job while the other thread remains busy, the completed thread steals the tasks from the busy thread and begins working on them.

The basic purpose of using Fork/Join is to improve application performance by taking use of multiple processors. You’ve probably heard of the “divide and conquer” strategy. The Fork/Join system operates similarly.

Let’s understand the basics about Fork and Join. What is Fork and What is Join with some small example.

Table of Contents

  • What is Fork in Java?
  • What is Join in Java?
  • Pseudocode of Fork/Join
  • ForkJoinPool
  • Implementation of Fork/Join by extending RecursiveTask
    • Syntax of RecursiveTask in Fork/Join
    • Example of RecursiveTask in Fork/Join
  • Implementation of Fork/Join by extending RecursiveAction
    • Syntax of RecursiveAction in Fork/Join
    • Example of RecursiveAction in Fork/Join
  • Difference between RecursiveAction and RecursiveTask in java

What is Fork in Java?

In Java, Fork is the process of dividing a work into smaller tasks that are also independent of one another. These tasks can also be performed in parallel.

What is Join in Java?

The Join idea is used when a work is separated into smaller pieces and executed in parallel. Once all subtasks have completed their execution, the join process joins all the results; otherwise, the join will continue to wait.

Pseudocode of Fork/Join

There are a few things to think about. If your work is really small, you should not split it. It should be carried out immediately. If you work is larger, you should break it down into smaller chunks.

if (smaller work)
  do not split
else
  split work into pieces
  wait for the results

ForkJoinPool

Fork/Join is a framework that implements the ExecutorService interface. ForkJoinPool is the core of the this framework. ForkJoinPool implements the core work-stealing mechanism.

In case of ForkJoinPool, there is no separate thread for each sub-task. The task is stored in its own deque for ForkJoinPool.

Implementation of Fork/Join by extending RecursiveTask

A task can return a value if you use a RecursiveTask.

Syntax of RecursiveTask in Fork/Join


pubilc class RecursiveTaskDemo extends RecursiveTask {

   @Override
   protected Long compute() { 
		return null; 
   }
}

Example of RecursiveTask in Fork/Join


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

public class RecursiveTaskExample extends RecursiveTask {

	private long[] array;
	private int startIndex;
	private int length;

	public RecursiveTaskExample(int startIndex, int length, long[] array) {
		this.startIndex = startIndex;
		this.length = length;
		this.array = array;
	}

	@Override
	protected Long compute() {
		int processingSizeMin = 100;
		long total = 0;
		if (length - startIndex < processingSizeMin) {
			for (int i = startIndex; i < length; i++) {
				total += array[i];
			}
		} else {
			int mid = (startIndex + length) / 2;
			RecursiveTaskExample recursiveTask1 = new RecursiveTaskExample(startIndex, mid, array);
			RecursiveTaskExample recursiveTask2 = new RecursiveTaskExample(mid, length, array);
			recursiveTask1.fork();
			recursiveTask2.fork();

			total = recursiveTask1.join() + recursiveTask2.join();
		}

		return total;
	}

	public static void main(String[] args) {

		final int maxSize = 10000;
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		long[] array = new long[maxSize];
		for (int i = 0; i < maxSize; i++) {
			array[i] = i;
		}
		RecursiveTaskExample recursiveTask = new RecursiveTaskExample(0, array.length, array);
		long total = forkJoinPool.invoke(recursiveTask);
		System.out.println("Sum of elements = " + total);
	}
}

Output:
Sum of elements = 49995000

Implementation of Fork/Join by extending RecursiveAction

A task doesn’t return a value if you use a RecursiveAction.

Syntax of RecursiveAction in Fork/Join


public class RecursiveActionDemo extends RecursiveAction {
   
   @Override
   protected void compute() {
	// Your code here
   }
}

Example of RecursiveAction in Fork/Join


import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

public class RecursiveActionExample extends RecursiveAction {

	long[] array;
	int startIndex;
	int length;

	public RecursiveActionExample(int startIndex, int length, long[] array) {
		this.startIndex = startIndex;
		this.length = length;
		this.array = array;
	}

	@Override
	protected void compute() {

		int processingSizeMin = 100;
		if (length - startIndex < processingSizeMin) {
			for (int i = startIndex; i < length; i++) {
				array[i] = array[i] * array[i];
			}
		} else {
			int middleValue = (startIndex + length) / 2;
			invokeAll(new RecursiveActionExample(startIndex, middleValue, array),
					new RecursiveActionExample(middleValue, length, array));
		}
	}

	public static void main(String[] args) {

		final int maxLength = 100000;
		ForkJoinPool joinPool = new ForkJoinPool();
		long[] inputArray = new long[maxLength];
		for (int i = 0; i < maxLength; i++) {
			inputArray[i] = i;
		}
		RecursiveActionExample recursiveActionExample = new RecursiveActionExample(0, inputArray.length, inputArray);
		joinPool.invoke(recursiveActionExample);
		System.out.println("Parallelism Level > " + joinPool.getParallelism());

	}
}

Output:
Parallelism Level > 4

Difference between RecursiveAction and RecursiveTask in java

#RecursiveTask RecursiveAction
1The method of this class returns a value if you submit the task using RecursiveTask.But the method of this class doesn’t return any value in case of RecursiveAction.
2protected abstract V compute();
You can change the return type as per your requirement.
protected abstract void compute()
The return type is void.

Also Read:
Multithreading in Java
Difference between Callable and Runnable

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • More
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)

Also Read

Java

Post navigation

Previous Post: Java 11 new Features (With example Programs)

More Related Articles

Java LinkedList Java LinkedList Java
Difference between Interface and Abstract class Difference between Interface and Abstract class Differences
Exception Handling in Java Exception Handling in Java Java
Java Switch Case Java Switch Case Java
Java 11 new Features (With example Programs) Java 11 new Features (With example Programs) Important
What is Array in Java? Types of array in Java What is Array in Java? Types of array in Java Java

Related Posts

  • Java LinkedList
    Java LinkedList Java
  • Difference between Interface and Abstract class
    Difference between Interface and Abstract class Differences
  • Exception Handling in Java
    Exception Handling in Java Java
  • Java Switch Case
    Java Switch Case Java
  • Java 11 new Features (With example Programs)
    Java 11 new Features (With example Programs) Important
  • What is Array in Java? Types of array in Java
    What is Array in Java? Types of array in Java Java

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Recent Posts

  • Structured Vs Unstructured Data in Hindi | Key Difference
  • Jhansi Ki Rani Lakshmi Bai History, Story, Information in Hindi
  • Elon musk Hindi : एलन मस्क हिंदी में, Autobiography,  Net Worth
  • World Environment Day in Hindi : Objective, Importance, Theme
  • Thomas Edison Biography in Hindi – थॉमस एडिसन जीवनी
  • International Nurses Day in Hindi | नर्स दिवस क्यों मनाते हैं?
  • Fork/Join Framework in Java | RecursiveTask, RecursiveAction
  • DBMS in Hindi | DBMS क्या है? | DBMS की विशेषताएं और प्रकार
  • Servlet Tutorial
    Servlet Tutorial Servlet
  • Structured Vs Unstructured Data in Hindi | Key Difference
    Structured Vs Unstructured Data in Hindi | Key Difference Differences
  • Chhath Puja Story
    Chhath Puja History : क्यों मनाते हैं छठ महापर्व Festival
  • Kapil Sharma Show, Comedy Show in Hindi
    Kapil Sharma Show, Comedy Show in Hindi Biography
  • Real life Inspirational Stories in Hindi | Success story in Hindi
    Real life Inspirational Stories in Hindi | Success story in Hindi Biography
  • What is Mutual Fund?
    What is Mutual Fund? Important
  • Dynamic memory allocation in C, malloc, realloc, calloc and free
    Dynamic memory allocation in C, malloc, realloc, calloc and free Data Structure
  • Java Hibernate Framework Tutorial
    Java Hibernate Framework Tutorial | Hibernate For Beginners Hibernate
  • Java Tutorial
  • Servlet Tutorial
  • JSP Tutorial
  • Maven Tutorial
  • HTML Tutorial
  • Programs
  • Hindi/English Grammar
  • Difference Between ... and ...
  • HR Interview
  • Important Articles

Write to Us:
geekcer.code@gmail.com

  • About Us
  • Privacy and Policy
  • Disclaimer
  • Contact Us
  • Sitemap

Copyright © GeekCer 2022 All Rights reserved