1 |
dl |
1.1 |
/* |
2 |
|
|
* Written by Doug Lea with assistance from members of JCP JSR-166 |
3 |
|
|
* Expert Group and released to the public domain, as explained at |
4 |
jsr166 |
1.11 |
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
dl |
1.1 |
*/ |
6 |
|
|
|
7 |
|
|
package jsr166y; |
8 |
|
|
|
9 |
|
|
/** |
10 |
jsr166 |
1.10 |
* A recursive result-bearing {@link ForkJoinTask}. |
11 |
|
|
* |
12 |
|
|
* <p>For a classic example, here is a task computing Fibonacci numbers: |
13 |
dl |
1.1 |
* |
14 |
jsr166 |
1.4 |
* <pre> {@code |
15 |
|
|
* class Fibonacci extends RecursiveTask<Integer> { |
16 |
dl |
1.1 |
* final int n; |
17 |
jsr166 |
1.3 |
* Fibonacci(int n) { this.n = n; } |
18 |
dl |
1.1 |
* Integer compute() { |
19 |
jsr166 |
1.4 |
* if (n <= 1) |
20 |
dl |
1.1 |
* return n; |
21 |
|
|
* Fibonacci f1 = new Fibonacci(n - 1); |
22 |
|
|
* f1.fork(); |
23 |
|
|
* Fibonacci f2 = new Fibonacci(n - 2); |
24 |
|
|
* return f2.compute() + f1.join(); |
25 |
|
|
* } |
26 |
jsr166 |
1.4 |
* }}</pre> |
27 |
dl |
1.1 |
* |
28 |
|
|
* However, besides being a dumb way to compute Fibonacci functions |
29 |
|
|
* (there is a simple fast linear algorithm that you'd use in |
30 |
|
|
* practice), this is likely to perform poorly because the smallest |
31 |
|
|
* subtasks are too small to be worthwhile splitting up. Instead, as |
32 |
|
|
* is the case for nearly all fork/join applications, you'd pick some |
33 |
|
|
* minimum granularity size (for example 10 here) for which you always |
34 |
jsr166 |
1.2 |
* sequentially solve rather than subdividing. |
35 |
dl |
1.1 |
* |
36 |
jsr166 |
1.5 |
* @since 1.7 |
37 |
|
|
* @author Doug Lea |
38 |
dl |
1.1 |
*/ |
39 |
|
|
public abstract class RecursiveTask<V> extends ForkJoinTask<V> { |
40 |
dl |
1.9 |
private static final long serialVersionUID = 5232453952276485270L; |
41 |
dl |
1.1 |
|
42 |
|
|
/** |
43 |
jsr166 |
1.8 |
* The result of the computation. |
44 |
dl |
1.1 |
*/ |
45 |
|
|
V result; |
46 |
|
|
|
47 |
|
|
/** |
48 |
jsr166 |
1.2 |
* The main computation performed by this task. |
49 |
dl |
1.1 |
*/ |
50 |
|
|
protected abstract V compute(); |
51 |
|
|
|
52 |
|
|
public final V getRawResult() { |
53 |
|
|
return result; |
54 |
|
|
} |
55 |
|
|
|
56 |
|
|
protected final void setRawResult(V value) { |
57 |
|
|
result = value; |
58 |
|
|
} |
59 |
|
|
|
60 |
|
|
/** |
61 |
jsr166 |
1.7 |
* Implements execution conventions for RecursiveTask. |
62 |
dl |
1.1 |
*/ |
63 |
|
|
protected final boolean exec() { |
64 |
|
|
result = compute(); |
65 |
|
|
return true; |
66 |
|
|
} |
67 |
|
|
|
68 |
|
|
} |