ForkJoinTask.
For example, here is a task-based program for computing Factorials:
import java.util.concurrent.RecursiveTask;
import java.math.BigInteger;
public class Factorial {
static class FactorialTask extends RecursiveTask<BigInteger> {
private final int from, to;
FactorialTask(int from, int to) { this.from = from; this.to = to; }
protected BigInteger compute() {
int range = to - from;
if (range == 0) { // base case
return BigInteger.valueOf(from);
} else if (range == 1) { // too small to parallelize
return BigInteger.valueOf(from).multiply(BigInteger.valueOf(to));
} else { // split in half
int mid = from + range / 2;
FactorialTask leftTask = new FactorialTask(from, mid);
leftTask.fork(); // perform about half the work locally
return new FactorialTask(mid + 1, to).compute()
.multiply(leftTask.join());
}
}
}
static BigInteger factorial(int n) { // uses ForkJoinPool.commonPool()
return (n <= 1) ? BigInteger.ONE : new FactorialTask(1, n).invoke();
}
public static void main(String[] args) {
System.out.println(factorial(Integer.parseInt(args[0])));
}
}
| Modifier and Type | Field and Description |
|---|---|
| pack-priv V | |
| private static final long |
| Access | Constructor and Description |
|---|---|
| public |
| Modifier and Type | Method and Description |
|---|---|
| protected abstract V | |
| protected final boolean | exec()
Implements abstract java. Implements execution conventions for RecursiveTask. |
| public final V | getRawResult()
Implements abstract java. Returns the result that would be returned by |
| protected final void | setRawResult(V value)
Implements abstract java. Forces the given value to be returned as a result. |
| result | back to summary |
|---|---|
pack-priv V result
| |
| serialVersionUID | back to summary |
|---|---|
| private static final long serialVersionUID | |
| RecursiveTask | back to summary |
|---|---|
| public RecursiveTask() Constructor for subclasses to call. | |
| compute | back to summary |
|---|---|
| protected abstract V compute() The main computation performed by this task.
| |
| exec | back to summary |
|---|---|
| protected final boolean exec() Implements abstract java. Implements execution conventions for RecursiveTask. | |
| getRawResult | back to summary |
|---|---|
| public final V getRawResult() Implements abstract java. Doc from java. Returns the result that would be returned by | |
| setRawResult | back to summary |
|---|---|
| protected final void setRawResult(V value) Implements abstract java. Doc from java. Forces the given value to be returned as a result. This method is designed to support extensions, and should not in general be called otherwise. | |