Java Reference
In-Depth Information
// Multiple numbers. Divide them into many single tasks. Keep the references of
// all tasks to call thier join() method later
List<RecursiveTask<Long>>forks = new ArrayList<>();
for(int i = 0; i < this.count; i++) {
RandomIntSum subTask = new RandomIntSum(1);
subTask.fork(); // Launch the subtask
// Keep the subTask references to combine the results later
forks.add(subTask);
}
// Now wait for all subtasks to finish and combine the result
for(RecursiveTask<Long> subTask : forks) {
result = result + subTask.join();
}
return result;
}
public int getRandomInteger() {
// Generate the next randon integer between 1 and 100
int n = randGenerator.nextInt(100) + 1;
System.out.println("Generated a random integer: " + n);
return n;
}
}
The class is named
RandomIntSum
. It extends
RecursiveTask<Long>
because it yields a result of the type
Long
.
The result is the sum of all random integers. It declares a
randGenerator
instance variable that is used to generate a
random number. The
count
instance variable stores the number of random numbers that you want to use. The value
for the
count
instance variable is set in the constructor.
The
getRandomInteger()
method of the
RandomIntSum
class generates a random integer between 1 and 100,
prints the integer value on the standard output, and returns the random integer.
The
compute()
method contains the main logic to perform the task. If the number of random numbers to use is
one, it computes the result and returns it to the caller. If the number of random number is more than one, it launches
as many subtasks as the number of random numbers. Note that if you use ten random numbers, it will launch ten
subtasks because each random number can be computed independently. Finally, you need to combine the results
from all subtasks. Therefore, you need to keep the references of the subtask for later use. You used a
List
to store
the references of all subtasks. Note the use of the
fork()
method to launch a subtask. The following snippet of code
performs this logic:
List<RecursiveTask<Long>>forks = new ArrayList<>();
for(int i = 0; i < this.count; i++) {
RandomIntSum subTask = new RandomIntSum(1);
subTask.fork(); // Launch the subtask
// Keep the subTask references to combine the results at the end
forks.add(subTask);
}