jsr166y.forkjoin
public abstract class RecursiveTask<V> extends ForkJoinTask<V>
For a classic example, here is a task computing Fibonacci numbers:
class Fibonacci extends RecursiveTask<Integer> { final int n; Fibonnaci(int n) { this.n = n; } Integer compute() { if (n <= 1) return n; Fibonacci f1 = new Fibonacci(n - 1); f1.fork(); Fibonacci f2 = new Fibonacci(n - 2); return f2.forkJoin() + f1.join(); } }However, besides being a dumb way to compute Fibonacci functions (there is a simple fast linear algorithm that you'd use in practice), this is likely to perform poorly because the smallest subtasks are too small to be worthwhile splitting up. Instead, as is the case for nearly all fork/join applications, you'd pick some minimum granularity size (for example 10 here) for which you always sequentially solve rather than subdividing. Note also the use of f2.forkJoin() instead of f2.fork(); f2.join(), which is both more convenient and more efficient.
Constructor and Description |
---|
RecursiveTask() |
Modifier and Type | Method and Description |
---|---|
protected abstract V |
compute()
The main computation performed by this task.
|
java.lang.Throwable |
exec()
Immediately commences execution of this task by the current
worker thread unless already cancelled, returning any exception
thrown by its compute method.
|
void |
finish(V result)
Completes this task, and if not already aborted or cancelled,
returning the given result upon join and related
operations.
|
void |
finishExceptionally(java.lang.Throwable ex)
Completes this task abnormally, and if not already aborted or
cancelled, causes it to throw the given exception upon
join and related operations.
|
V |
forkJoin()
Equivalent in effect to the sequence fork(); join();
but may be more efficient.
|
V |
rawResult()
Returns the result that would be returned by join, or
null if this task is not known to have been completed.
|
void |
reinitialize()
Resets the internal bookkeeping state of this task, allowing a
subsequent fork.
|
cancel, fork, getException, isCancelled, isDone, isStolen, join, quietlyJoin
protected abstract V compute()
public final V rawResult()
ForkJoinTask
rawResult
in class ForkJoinTask<V>
public final V forkJoin()
ForkJoinTask
forkJoin
in class ForkJoinTask<V>
public final java.lang.Throwable exec()
ForkJoinTask
exec
in class ForkJoinTask<V>
public final void finish(V result)
ForkJoinTask
finish
in class ForkJoinTask<V>
result
- the result to returnpublic final void finishExceptionally(java.lang.Throwable ex)
ForkJoinTask
finishExceptionally
in class ForkJoinTask<V>
ex
- the exception to throw. While not necessarily
statically enforced, this must be a RuntimeException or Error.public final void reinitialize()
ForkJoinTask
reinitialize
in class ForkJoinTask<V>