Java Reference
In-Depth Information
Step 4: Creating the Fork/Join Task
You need to create an instance of your task.
MyTask task = MyTask();
Step 5: Submitting the Task to the Fork/Join Pool for Execution
You need to call the
invoke()
method of the
ForkJoinPool
class, passing your task as an argument. The
invoke()
method will return the result of the task if your task returns a result. The following statement will execute your task:
long result = pool.invoke(task);
A Fork/Join Example
Let's consider a simple example of using the fork/join framework. Your task will generate a few random integers and
compute their sum. Listing 6-58 has the complete code for your task.
Listing 6-58.
A ForkJoinTask Class to Compute the Sum of a Few Random Integers
// RandomIntSum.java
package com.jdojo.threads;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.RecursiveTask;
public class RandomIntSum extends RecursiveTask<Long> {
private static Random randGenerator = new Random();
private int count;
public RandomIntSum(int count) {
this.count = count;
}
@Override
protected Long compute() {
long result = 0;
if (this.count <= 0) {
return 0L; // We do not have anything to do
}
if (this.count == 1) {
// Compute the number directly and return the result
return (long) this.getRandomInteger();
}