Home  >  Java 7

RecursiveTask Java Example

By Arvind Rai, January 08, 2014
java.util.concurrent.RecursiveTask has been introduced in JDK 7 and is the part of fork join framework. RecursiveTask is an abstract class and it extends ForkJoinTask. The is a method compute() in RecursiveTask class. The implementing class will override this method. What this method will do is that it will be called reclusively. To show an example, we will calculate fibonacci number using RecursiveTask.

compute() in Java RecursiveTask

This is the main method that performs the computation in RecursiveTask .

exec() in Java RecursiveTask

exec() returns Boolean values and implements execution conventions.

getRawResult() in Java RecursiveTask

This method returns the result which is actually returned by ForkJoinTask.join(). The use of getRawResult() is for debugging only.

setRawResult(V value) in Java RecursiveTask

This method forces the arguments value to be returned by getRawResult(). This methd should be used for only this purpose.


Fibonacci Number

One good use of RecursiveTask is getting fibonacci number addition . Fibonacci numbers are a series in which the next number is the addition of previous two numbers as below.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ...
Now find the example of RecursiveTask which calculates the fibonacci number .
RecursiveTaskDemo.java
package com.concretepage.util.concurrent;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
public class RecursiveTaskDemo {
	public static void main(String[] args) {
		FibonacciCal fibonacciCal = new FibonacciCal(12);
		ForkJoinPool pool = new ForkJoinPool();
		int i = pool.invoke(fibonacciCal);
		System.out.println(i);
	}
}
class FibonacciCal extends RecursiveTask<Integer>{
	private static final long serialVersionUID = 1L;
	final int num;
	FibonacciCal(int num) { this.num = num; }
	@Override
	protected Integer compute() {
	     if (num <= 1){
	        return num;
	     }
	     FibonacciCal fcal1 = new FibonacciCal(num - 1);
	     fcal1.fork();
	     FibonacciCal fcal2 = new FibonacciCal(num - 2);
	     return fcal2.compute() + fcal1.join();
	}
}
 
In the example we have a class FibonacciCal, which is overriding compute() method of RecursiveTask in java. Pass a number and it will calculate the fibonacci number for that given number.
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us