ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/test/loops/BinaryAsyncAction.java
Revision: 1.20
Committed: Mon Sep 14 16:47:43 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.19: +0 -2 lines
Log Message:
whitespace

File Contents

# User Rev Content
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.6 * http://creativecommons.org/publicdomain/zero/1.0/
5 dl 1.1 */
6    
7     import java.util.concurrent.*;
8     import java.util.concurrent.atomic.*;
9    
10     /**
11     * AsyncActions that are always linked in binary parent-child
12     * relationships. Compared to Recursive tasks, BinaryAsyncActions may
13     * have smaller stack space footprints and faster completion mechanics
14     * but higher per-task footprints. Compared to LinkedAsyncActions,
15     * BinaryAsyncActions are simpler to use and have less overhead in
16 jsr166 1.16 * typical usages but are restricted to binary computation trees.
17 dl 1.1 *
18 jsr166 1.11 * <p>Upon construction, a BinaryAsyncAction does not bear any
19 dl 1.1 * linkages. For non-root tasks, links must be established using
20 jsr166 1.12 * method {@link #linkSubtasks} before use.
21 dl 1.1 *
22 jsr166 1.7 * <p><b>Sample Usage.</b> A version of Fibonacci:
23 dl 1.1 * <pre>
24     * class Fib extends BinaryAsyncAction {
25     * final int n;
26     * int result;
27     * Fib(int n) { this.n = n; }
28     * protected void compute() {
29     * if (n &gt; 1) {
30 jsr166 1.9 * linkAndForkSubtasks(new Fib(n-1), new Fib(n-2));
31 dl 1.1 * else {
32 jsr166 1.9 * result = n; // fib(0)==0; fib(1)==1
33     * complete();
34 dl 1.1 * }
35     * }
36     * protected void onComplete(BinaryAsyncAction x, BinaryAsyncAction y) {
37 jsr166 1.8 * result = ((Fib)x).result + ((Fib)y).result;
38 dl 1.1 * }
39     * }
40     * </pre>
41 jsr166 1.14 * An alternative, and usually faster, strategy is to instead use a
42 dl 1.1 * loop to fork subtasks:
43     * <pre>
44     * protected void compute() {
45     * Fib f = this;
46     * while (f.n &gt; 1) {
47 jsr166 1.9 * Fib left = new Fib(f.n - 1);
48     * Fib right = new Fib(f.n - 2);
49     * f.linkSubtasks(left, right);
50     * right.fork(); // fork right
51     * f = left; // loop on left
52 dl 1.1 * }
53     * f.result = f.n;
54     * f.complete();
55     * }
56     * }
57     * </pre>
58     */
59     public abstract class BinaryAsyncAction extends ForkJoinTask<Void> {
60 jsr166 1.19 private volatile int controlState;
61    
62     static final AtomicIntegerFieldUpdater<BinaryAsyncAction> controlStateUpdater =
63 dl 1.18 AtomicIntegerFieldUpdater.newUpdater(BinaryAsyncAction.class, "controlState");
64 jsr166 1.19
65 dl 1.1 /**
66     * Parent to propagate completion; nulled after completion to
67     * avoid retaining entire tree as garbage
68     */
69     private BinaryAsyncAction parent;
70    
71     /**
72     * Sibling to access on subtask joins, also nulled after completion.
73     */
74     private BinaryAsyncAction sibling;
75    
76     /**
77     * Creates a new action. Unless this is a root task, you will need
78 jsr166 1.12 * to link it using method {@link #linkSubtasks} before forking as
79 dl 1.1 * a subtask.
80     */
81     protected BinaryAsyncAction() {
82     }
83    
84     public final Void getRawResult() { return null; }
85     protected final void setRawResult(Void mustBeNull) { }
86    
87     /**
88     * Establishes links for the given tasks to have the current task
89     * as parent, and each other as siblings.
90     * @param x one subtask
91     * @param y the other subtask
92 jsr166 1.14 * @throws NullPointerException if either argument is null
93 dl 1.1 */
94     public final void linkSubtasks(BinaryAsyncAction x, BinaryAsyncAction y) {
95     x.parent = y.parent = this;
96     x.sibling = y;
97     y.sibling = x;
98     }
99    
100     /**
101 jsr166 1.12 * Overridable callback action triggered upon {@code complete} of
102 dl 1.1 * subtasks. Upon invocation, both subtasks have completed.
103 jsr166 1.12 * After return, this task {@code isDone} and is joinable by
104 jsr166 1.5 * other tasks. The default version of this method does nothing.
105     * But it may be overridden in subclasses to perform some action
106     * (for example a reduction) when this task is completes.
107 dl 1.1 * @param x one subtask
108     * @param y the other subtask
109     */
110     protected void onComplete(BinaryAsyncAction x, BinaryAsyncAction y) {
111     }
112    
113     /**
114     * Overridable callback action triggered by
115 jsr166 1.12 * {@code completeExceptionally}. Upon invocation, this task has
116 dl 1.1 * aborted due to an exception (accessible via
117 jsr166 1.12 * {@code getException}). If this method returns {@code true},
118 dl 1.1 * the exception propagates to the current task's
119     * parent. Otherwise, normal completion is propagated. The
120     * default version of this method does nothing and returns
121 jsr166 1.12 * {@code true}.
122 dl 1.1 * @return true if this task's exception should be propagated to
123 jsr166 1.15 * this task's parent
124 dl 1.1 */
125     protected boolean onException() {
126     return true;
127     }
128    
129     /**
130 jsr166 1.12 * Equivalent in effect to invoking {@link #linkSubtasks} and then
131 dl 1.1 * forking both tasks.
132     * @param x one subtask
133     * @param y the other subtask
134     */
135     public void linkAndForkSubtasks(BinaryAsyncAction x, BinaryAsyncAction y) {
136     linkSubtasks(x, y);
137     y.fork();
138     x.fork();
139     }
140    
141     /** Basic per-task complete */
142     private void completeThis() {
143     super.complete(null);
144     }
145    
146     /** Basic per-task completeExceptionally */
147     private void completeThisExceptionally(Throwable ex) {
148     super.completeExceptionally(ex);
149     }
150    
151     /*
152     * We use one bit join count on taskState. The first arriving
153     * thread CAS's from 0 to 1. The second ultimately sets status
154     * to signify completion.
155     */
156    
157     /**
158     * Completes this task, and if this task has a sibling that is
159 jsr166 1.12 * also complete, invokes {@code onComplete} of parent task, and so
160 dl 1.1 * on. If an exception is encountered, tasks instead
161 jsr166 1.12 * {@code completeExceptionally}.
162 dl 1.1 */
163     public final void complete() {
164     // todo: Use tryUnfork without possibly blowing stack
165     BinaryAsyncAction a = this;
166     for (;;) {
167     BinaryAsyncAction s = a.sibling;
168     BinaryAsyncAction p = a.parent;
169     a.sibling = null;
170     a.parent = null;
171     a.completeThis();
172 dl 1.18 if (p == null || p.compareAndSetControlState(0, 1))
173 dl 1.1 break;
174     try {
175     p.onComplete(a, s);
176 jsr166 1.3 } catch (Throwable rex) {
177 dl 1.1 p.completeExceptionally(rex);
178     return;
179     }
180     a = p;
181     }
182     }
183    
184     /**
185     * Completes this task abnormally. Unless this task already
186     * cancelled or aborted, upon invocation, this method invokes
187 jsr166 1.12 * {@code onException}, and then, depending on its return value,
188 jsr166 1.13 * completes parent (if one exists) exceptionally or normally. To
189 dl 1.1 * avoid unbounded exception loops, this method aborts if an
190 jsr166 1.12 * exception is encountered in any {@code onException}
191 dl 1.1 * invocation.
192     * @param ex the exception to throw when joining this task
193     * @throws NullPointerException if ex is null
194     * @throws Throwable if any invocation of
195 jsr166 1.14 * {@code onException} does so
196 dl 1.1 */
197     public final void completeExceptionally(Throwable ex) {
198     BinaryAsyncAction a = this;
199     while (!a.isCompletedAbnormally()) {
200     a.completeThisExceptionally(ex);
201     BinaryAsyncAction s = a.sibling;
202     if (s != null)
203     s.cancel(false);
204     if (!a.onException() || (a = a.parent) == null)
205     break;
206     }
207     }
208    
209     /**
210     * Returns this task's parent, or null if none or this task
211     * is already complete.
212 jsr166 1.14 * @return this task's parent, or null if none
213 dl 1.1 */
214     public final BinaryAsyncAction getParent() {
215     return parent;
216     }
217    
218     /**
219     * Returns this task's sibling, or null if none or this task is
220     * already complete.
221 jsr166 1.14 * @return this task's sibling, or null if none
222 dl 1.1 */
223     public BinaryAsyncAction getSibling() {
224     return sibling;
225     }
226    
227     /**
228     * Resets the internal bookkeeping state of this task, erasing
229     * parent and child linkages.
230     */
231     public void reinitialize() {
232     parent = sibling = null;
233     super.reinitialize();
234     }
235    
236     /**
237     * Gets the control state, which is initially zero, or negative if
238     * this task has completed or cancelled. Once negative, the value
239     * cannot be changed.
240     * @return control state
241     */
242     protected final int getControlState() {
243     return controlState;
244     }
245    
246     /**
247     * Atomically sets the control state to the given updated value if
248     * the current value is and equal to the expected value.
249     * @param expect the expected value
250     * @param update the new value
251     * @return true if successful
252     */
253 jsr166 1.2 protected final boolean compareAndSetControlState(int expect,
254 dl 1.1 int update) {
255     return controlStateUpdater.compareAndSet(this, expect, update);
256     }
257    
258     /**
259     * Attempts to set the control state to the given value, failing if
260     * this task is already completed or the control state value would be
261     * negative.
262     * @param value the new value
263     * @return true if successful
264     */
265     protected final void setControlState(int value) {
266     controlState = value;
267     }
268    
269     /**
270 jsr166 1.14 * Increments the control state.
271 dl 1.1 * @param value the new value
272     */
273     protected final void incrementControlState() {
274     controlStateUpdater.incrementAndGet(this);
275     }
276    
277     /**
278 jsr166 1.14 * Decrements the control state.
279 dl 1.1 * @return true if successful
280     */
281     protected final void decrementControlState() {
282     controlStateUpdater.decrementAndGet(this);
283     }
284     }