Java Reference
In-Depth Information
Once all subtasks are launched, you need to wait for all subtasks to finish and combine all random integers to get
the sum. The following snippet of code performs this logic. Note the use of the join() method, which will make the
current task wait for the subtask to finish.
for(RecursiveTask<Long> subTask : forks) {
result = result + subTask.join();
}
Finally, the compute() method returns the result, which is the sum of all the random integers.
Listing 6-59 has the code to execute a task, which is an instance of the RandomIntSum class.
Listing 6-59. Using a Fork/Join Pool to Execute a Fork/Join Task
// ForkJoinTest.java
package com.jdojo.threads;
import java.util.concurrent.ForkJoinPool;
public class ForkJoinTest {
public static void main(String[] args) {
// Create a ForkJoinPool to run the task
ForkJoinPool pool = new ForkJoinPool();
// Create an instance of the task
RandomIntSum task = new RandomIntSum(3);
// Run the task
long sum = pool.invoke(task);
System.out.println("Sum is " + sum);
}
}
(You may get a different output.)
Generated a random integer: 62
Generated a random integer: 46
Generated a random integer: 90
Sum is 198
This is a very simple example of using the fork/join framework. You are advised to explore the fork/join framework
classes to know more about the framework. Inside the compute() method of your task, you can have complex logic
to divide tasks into subtasks. Unlike in this example, you may not know in advance how many subtasks you need to
launch. You may launch a subtask that may launch another subtask and so on.
Search WWH ::




Custom Search