It's a framework used to speed up calculations on computers with more than one processing unit.
It isn't suitable for any kind of task, but only if:
Here's an example to sum a list of numbers:
import java.util.concurrent.RecursiveTask; /** * This class split the job of summing up a list of number in * smaller tasks, that can be executed using different processing units, in order * to make it faster. * @author Davis Fiore * */ public class SumCalculator extends RecursiveTask<Integer> { private int[] nums; private int availProcs; private int start; private int end; /** * Constructor called the first for the entire operation * @param nums List of numbers * @param procs Processing units available */ public SumCalculator(int[] nums, int procs) { this(nums, procs, 0, nums.length); } /** * Constructor used to execute a subtask * @param nums List of numbers * @param procs Processing units available * @param start Start summing up from this position * @param end End summing up at this position */ public SumCalculator(int[] nums, int procs, int start, int end) { this.nums = nums; this.availProcs = procs; this.start = start; this.end = end; } /** * This method split the calculation, when the task is too big and there are * processing units available, else execute the partial calculation and return * the result * @return Result of the sum for a task or sub-task */ @Override protected Integer compute() { int partSum = 0; // Check how big the chunk of data is and if there are enought threads if ((end - start) <= nums.length/availProcs) { // The data is small enought, so execute here the calculation for (int i = start; i < end; i++) partSum += nums[i]; return partSum; } else { // The data need to be splitted in smaller parts int mid = (end - start)/2; // This is the first part SumCalculator firstCalc = new SumCalculator(nums, availProcs, start, mid); firstCalc.fork(); // This is the second part SumCalculator secondCalc = new SumCalculator(nums, availProcs, mid, end); partSum = secondCalc.compute(); // Join both the results return firstCalc.join() + partSum; } } } import java.util.Random; import java.util.concurrent.ForkJoinPool; /** * Main class to sum a list of numbers using the fork/join framework * @author Davis Fiore * */ public class App { /** * Main method to sum a list of numbers * @param args */ public static void main(String[] args) { // Initialization int[] nums = new int[100]; Random rnd = new Random(); // Get number of processors int availProcs = Runtime.getRuntime().availableProcessors(); // Get some random numbers to sum for (int i = 0; i < 100; i++) { nums[i] = rnd.nextInt(10); } // Calculate sum using fork/join ForkJoinPool pool = new ForkJoinPool(availProcs); int sum = pool.invoke(new SumCalculator(nums, availProcs)); // Show results System.out.printf("The sum is " + sum); } }
Copyright © 2013 Welcome to the website of Davis Fiore. All Rights Reserved.