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 |
|
|
* http://creativecommons.org/publicdomain/zero/1.0/ |
5 |
|
|
*/ |
6 |
|
|
|
7 |
|
|
package java.util.concurrent; |
8 |
|
|
|
9 |
dl |
1.55 |
import java.lang.invoke.MethodHandles; |
10 |
|
|
import java.lang.invoke.VarHandle; |
11 |
|
|
|
12 |
dl |
1.1 |
/** |
13 |
dl |
1.14 |
* A {@link ForkJoinTask} with a completion action performed when |
14 |
jsr166 |
1.38 |
* triggered and there are no remaining pending actions. |
15 |
|
|
* CountedCompleters are in general more robust in the |
16 |
dl |
1.15 |
* presence of subtask stalls and blockage than are other forms of |
17 |
|
|
* ForkJoinTasks, but are less intuitive to program. Uses of |
18 |
|
|
* CountedCompleter are similar to those of other completion based |
19 |
dl |
1.14 |
* components (such as {@link java.nio.channels.CompletionHandler}) |
20 |
|
|
* except that multiple <em>pending</em> completions may be necessary |
21 |
jsr166 |
1.31 |
* to trigger the completion action {@link #onCompletion(CountedCompleter)}, |
22 |
|
|
* not just one. |
23 |
jsr166 |
1.25 |
* Unless initialized otherwise, the {@linkplain #getPendingCount pending |
24 |
|
|
* count} starts at zero, but may be (atomically) changed using |
25 |
|
|
* methods {@link #setPendingCount}, {@link #addToPendingCount}, and |
26 |
|
|
* {@link #compareAndSetPendingCount}. Upon invocation of {@link |
27 |
dl |
1.1 |
* #tryComplete}, if the pending action count is nonzero, it is |
28 |
|
|
* decremented; otherwise, the completion action is performed, and if |
29 |
|
|
* this completer itself has a completer, the process is continued |
30 |
dl |
1.2 |
* with its completer. As is the case with related synchronization |
31 |
jsr166 |
1.5 |
* components such as {@link java.util.concurrent.Phaser Phaser} and |
32 |
|
|
* {@link java.util.concurrent.Semaphore Semaphore}, these methods |
33 |
|
|
* affect only internal counts; they do not establish any further |
34 |
|
|
* internal bookkeeping. In particular, the identities of pending |
35 |
|
|
* tasks are not maintained. As illustrated below, you can create |
36 |
jsr166 |
1.6 |
* subclasses that do record some or all pending tasks or their |
37 |
dl |
1.15 |
* results when needed. As illustrated below, utility methods |
38 |
|
|
* supporting customization of completion traversals are also |
39 |
|
|
* provided. However, because CountedCompleters provide only basic |
40 |
dl |
1.14 |
* synchronization mechanisms, it may be useful to create further |
41 |
dl |
1.15 |
* abstract subclasses that maintain linkages, fields, and additional |
42 |
|
|
* support methods appropriate for a set of related usages. |
43 |
dl |
1.1 |
* |
44 |
|
|
* <p>A concrete CountedCompleter class must define method {@link |
45 |
dl |
1.14 |
* #compute}, that should in most cases (as illustrated below), invoke |
46 |
|
|
* {@code tryComplete()} once before returning. The class may also |
47 |
jsr166 |
1.31 |
* optionally override method {@link #onCompletion(CountedCompleter)} |
48 |
|
|
* to perform an action upon normal completion, and method |
49 |
|
|
* {@link #onExceptionalCompletion(Throwable, CountedCompleter)} to |
50 |
|
|
* perform an action upon any exception. |
51 |
dl |
1.1 |
* |
52 |
dl |
1.4 |
* <p>CountedCompleters most often do not bear results, in which case |
53 |
|
|
* they are normally declared as {@code CountedCompleter<Void>}, and |
54 |
|
|
* will always return {@code null} as a result value. In other cases, |
55 |
|
|
* you should override method {@link #getRawResult} to provide a |
56 |
dl |
1.14 |
* result from {@code join(), invoke()}, and related methods. In |
57 |
|
|
* general, this method should return the value of a field (or a |
58 |
|
|
* function of one or more fields) of the CountedCompleter object that |
59 |
|
|
* holds the result upon completion. Method {@link #setRawResult} by |
60 |
|
|
* default plays no role in CountedCompleters. It is possible, but |
61 |
dl |
1.15 |
* rarely applicable, to override this method to maintain other |
62 |
dl |
1.14 |
* objects or fields holding result data. |
63 |
dl |
1.4 |
* |
64 |
dl |
1.1 |
* <p>A CountedCompleter that does not itself have a completer (i.e., |
65 |
|
|
* one for which {@link #getCompleter} returns {@code null}) can be |
66 |
|
|
* used as a regular ForkJoinTask with this added functionality. |
67 |
|
|
* However, any completer that in turn has another completer serves |
68 |
|
|
* only as an internal helper for other computations, so its own task |
69 |
|
|
* status (as reported in methods such as {@link ForkJoinTask#isDone}) |
70 |
|
|
* is arbitrary; this status changes only upon explicit invocations of |
71 |
jsr166 |
1.31 |
* {@link #complete}, {@link ForkJoinTask#cancel}, |
72 |
|
|
* {@link ForkJoinTask#completeExceptionally(Throwable)} or upon |
73 |
|
|
* exceptional completion of method {@code compute}. Upon any |
74 |
|
|
* exceptional completion, the exception may be relayed to a task's |
75 |
|
|
* completer (and its completer, and so on), if one exists and it has |
76 |
|
|
* not otherwise already completed. Similarly, cancelling an internal |
77 |
|
|
* CountedCompleter has only a local effect on that completer, so is |
78 |
|
|
* not often useful. |
79 |
dl |
1.1 |
* |
80 |
|
|
* <p><b>Sample Usages.</b> |
81 |
|
|
* |
82 |
|
|
* <p><b>Parallel recursive decomposition.</b> CountedCompleters may |
83 |
|
|
* be arranged in trees similar to those often used with {@link |
84 |
|
|
* RecursiveAction}s, although the constructions involved in setting |
85 |
dl |
1.4 |
* them up typically vary. Here, the completer of each task is its |
86 |
|
|
* parent in the computation tree. Even though they entail a bit more |
87 |
dl |
1.1 |
* bookkeeping, CountedCompleters may be better choices when applying |
88 |
|
|
* a possibly time-consuming operation (that cannot be further |
89 |
|
|
* subdivided) to each element of an array or collection; especially |
90 |
|
|
* when the operation takes a significantly different amount of time |
91 |
|
|
* to complete for some elements than others, either because of |
92 |
jsr166 |
1.27 |
* intrinsic variation (for example I/O) or auxiliary effects such as |
93 |
dl |
1.1 |
* garbage collection. Because CountedCompleters provide their own |
94 |
jsr166 |
1.58 |
* continuations, other tasks need not block waiting to perform them. |
95 |
dl |
1.1 |
* |
96 |
jsr166 |
1.58 |
* <p>For example, here is an initial version of a utility method that |
97 |
|
|
* uses divide-by-two recursive decomposition to divide work into |
98 |
|
|
* single pieces (leaf tasks). Even when work is split into individual |
99 |
|
|
* calls, tree-based techniques are usually preferable to directly |
100 |
|
|
* forking leaf tasks, because they reduce inter-thread communication |
101 |
|
|
* and improve load balancing. In the recursive case, the second of |
102 |
|
|
* each pair of subtasks to finish triggers completion of their parent |
103 |
dl |
1.1 |
* (because no result combination is performed, the default no-op |
104 |
jsr166 |
1.38 |
* implementation of method {@code onCompletion} is not overridden). |
105 |
jsr166 |
1.58 |
* The utility method sets up the root task and invokes it (here, |
106 |
|
|
* implicitly using the {@link ForkJoinPool#commonPool()}). It is |
107 |
|
|
* straightforward and reliable (but not optimal) to always set the |
108 |
|
|
* pending count to the number of child tasks and call {@code |
109 |
|
|
* tryComplete()} immediately before returning. |
110 |
dl |
1.1 |
* |
111 |
|
|
* <pre> {@code |
112 |
jsr166 |
1.58 |
* public static <E> void forEach(E[] array, Consumer<E> action) { |
113 |
|
|
* class Task extends CountedCompleter<Void> { |
114 |
|
|
* final int lo, hi; |
115 |
|
|
* Task(Task parent, int lo, int hi) { |
116 |
|
|
* super(parent); this.lo = lo; this.hi = hi; |
117 |
|
|
* } |
118 |
jsr166 |
1.59 |
* |
119 |
jsr166 |
1.58 |
* public void compute() { |
120 |
|
|
* if (hi - lo >= 2) { |
121 |
|
|
* int mid = (lo + hi) >>> 1; |
122 |
|
|
* // must set pending count before fork |
123 |
|
|
* setPendingCount(2); |
124 |
|
|
* new Task(this, mid, hi).fork(); // right child |
125 |
|
|
* new Task(this, lo, mid).fork(); // left child |
126 |
|
|
* } |
127 |
|
|
* else if (hi > lo) |
128 |
|
|
* action.accept(array[lo]); |
129 |
|
|
* tryComplete(); |
130 |
|
|
* } |
131 |
dl |
1.15 |
* } |
132 |
jsr166 |
1.58 |
* new Task(null, 0, array.length).invoke(); |
133 |
jsr166 |
1.21 |
* }}</pre> |
134 |
dl |
1.1 |
* |
135 |
|
|
* This design can be improved by noticing that in the recursive case, |
136 |
|
|
* the task has nothing to do after forking its right task, so can |
137 |
|
|
* directly invoke its left task before returning. (This is an analog |
138 |
jsr166 |
1.58 |
* of tail recursion removal.) Also, when the last action in a task |
139 |
|
|
* is to fork or invoke a subtask (a "tail call"), the call to {@code |
140 |
|
|
* tryComplete()} can be optimized away, at the cost of making the |
141 |
|
|
* pending count look "off by one". |
142 |
dl |
1.1 |
* |
143 |
|
|
* <pre> {@code |
144 |
jsr166 |
1.58 |
* public void compute() { |
145 |
|
|
* if (hi - lo >= 2) { |
146 |
|
|
* int mid = (lo + hi) >>> 1; |
147 |
|
|
* setPendingCount(1); // not off by one ! |
148 |
|
|
* new Task(this, mid, hi).fork(); // right child |
149 |
|
|
* new Task(this, lo, mid).compute(); // direct invoke |
150 |
|
|
* } else { |
151 |
|
|
* if (hi > lo) |
152 |
|
|
* action.accept(array[lo]); |
153 |
|
|
* tryComplete(); |
154 |
|
|
* } |
155 |
jsr166 |
1.61 |
* }}</pre> |
156 |
dl |
1.1 |
* |
157 |
jsr166 |
1.52 |
* As a further optimization, notice that the left task need not even exist. |
158 |
jsr166 |
1.60 |
* Instead of creating a new one, we can continue using the original task, |
159 |
jsr166 |
1.31 |
* and add a pending count for each fork. Additionally, because no task |
160 |
|
|
* in this tree implements an {@link #onCompletion(CountedCompleter)} method, |
161 |
jsr166 |
1.58 |
* {@code tryComplete} can be replaced with {@link #propagateCompletion}. |
162 |
dl |
1.1 |
* |
163 |
|
|
* <pre> {@code |
164 |
jsr166 |
1.58 |
* public void compute() { |
165 |
|
|
* int n = hi - lo; |
166 |
|
|
* for (; n >= 2; n /= 2) { |
167 |
|
|
* addToPendingCount(1); |
168 |
|
|
* new Task(this, lo + n/2, lo + n).fork(); |
169 |
|
|
* } |
170 |
|
|
* if (n > 0) |
171 |
|
|
* action.accept(array[lo]); |
172 |
|
|
* propagateCompletion(); |
173 |
jsr166 |
1.61 |
* }}</pre> |
174 |
jsr166 |
1.58 |
* |
175 |
|
|
* When pending counts can be precomputed, they can be established in |
176 |
|
|
* the constructor: |
177 |
|
|
* |
178 |
|
|
* <pre> {@code |
179 |
|
|
* public static <E> void forEach(E[] array, Consumer<E> action) { |
180 |
|
|
* class Task extends CountedCompleter<Void> { |
181 |
|
|
* final int lo, hi; |
182 |
|
|
* Task(Task parent, int lo, int hi) { |
183 |
|
|
* super(parent, 31 - Integer.numberOfLeadingZeros(hi - lo)); |
184 |
|
|
* this.lo = lo; this.hi = hi; |
185 |
|
|
* } |
186 |
jsr166 |
1.59 |
* |
187 |
jsr166 |
1.58 |
* public void compute() { |
188 |
|
|
* for (int n = hi - lo; n >= 2; n /= 2) |
189 |
|
|
* new Task(this, lo + n/2, lo + n).fork(); |
190 |
|
|
* action.accept(array[lo]); |
191 |
|
|
* propagateCompletion(); |
192 |
dl |
1.15 |
* } |
193 |
|
|
* } |
194 |
jsr166 |
1.58 |
* if (array.length > 0) |
195 |
|
|
* new Task(null, 0, array.length).invoke(); |
196 |
jsr166 |
1.46 |
* }}</pre> |
197 |
dl |
1.1 |
* |
198 |
jsr166 |
1.58 |
* Additional optimizations of such classes might entail specializing |
199 |
|
|
* classes for leaf steps, subdividing by say, four, instead of two |
200 |
|
|
* per iteration, and using an adaptive threshold instead of always |
201 |
|
|
* subdividing down to single elements. |
202 |
dl |
1.1 |
* |
203 |
dl |
1.15 |
* <p><b>Searching.</b> A tree of CountedCompleters can search for a |
204 |
|
|
* value or property in different parts of a data structure, and |
205 |
jsr166 |
1.26 |
* report a result in an {@link |
206 |
|
|
* java.util.concurrent.atomic.AtomicReference AtomicReference} as |
207 |
|
|
* soon as one is found. The others can poll the result to avoid |
208 |
|
|
* unnecessary work. (You could additionally {@linkplain #cancel |
209 |
|
|
* cancel} other tasks, but it is usually simpler and more efficient |
210 |
|
|
* to just let them notice that the result is set and if so skip |
211 |
|
|
* further processing.) Illustrating again with an array using full |
212 |
dl |
1.15 |
* partitioning (again, in practice, leaf tasks will almost always |
213 |
|
|
* process more than one element): |
214 |
|
|
* |
215 |
|
|
* <pre> {@code |
216 |
|
|
* class Searcher<E> extends CountedCompleter<E> { |
217 |
|
|
* final E[] array; final AtomicReference<E> result; final int lo, hi; |
218 |
|
|
* Searcher(CountedCompleter<?> p, E[] array, AtomicReference<E> result, int lo, int hi) { |
219 |
|
|
* super(p); |
220 |
|
|
* this.array = array; this.result = result; this.lo = lo; this.hi = hi; |
221 |
|
|
* } |
222 |
|
|
* public E getRawResult() { return result.get(); } |
223 |
|
|
* public void compute() { // similar to ForEach version 3 |
224 |
jsr166 |
1.47 |
* int l = lo, h = hi; |
225 |
dl |
1.15 |
* while (result.get() == null && h >= l) { |
226 |
|
|
* if (h - l >= 2) { |
227 |
|
|
* int mid = (l + h) >>> 1; |
228 |
|
|
* addToPendingCount(1); |
229 |
|
|
* new Searcher(this, array, result, mid, h).fork(); |
230 |
|
|
* h = mid; |
231 |
|
|
* } |
232 |
|
|
* else { |
233 |
|
|
* E x = array[l]; |
234 |
|
|
* if (matches(x) && result.compareAndSet(null, x)) |
235 |
|
|
* quietlyCompleteRoot(); // root task is now joinable |
236 |
|
|
* break; |
237 |
|
|
* } |
238 |
|
|
* } |
239 |
|
|
* tryComplete(); // normally complete whether or not found |
240 |
|
|
* } |
241 |
|
|
* boolean matches(E e) { ... } // return true if found |
242 |
|
|
* |
243 |
|
|
* public static <E> E search(E[] array) { |
244 |
|
|
* return new Searcher<E>(null, array, new AtomicReference<E>(), 0, array.length).invoke(); |
245 |
|
|
* } |
246 |
jsr166 |
1.28 |
* }}</pre> |
247 |
dl |
1.15 |
* |
248 |
|
|
* In this example, as well as others in which tasks have no other |
249 |
jsr166 |
1.51 |
* effects except to {@code compareAndSet} a common result, the |
250 |
|
|
* trailing unconditional invocation of {@code tryComplete} could be |
251 |
|
|
* made conditional ({@code if (result.get() == null) tryComplete();}) |
252 |
dl |
1.15 |
* because no further bookkeeping is required to manage completions |
253 |
|
|
* once the root task completes. |
254 |
|
|
* |
255 |
dl |
1.1 |
* <p><b>Recording subtasks.</b> CountedCompleter tasks that combine |
256 |
|
|
* results of multiple subtasks usually need to access these results |
257 |
jsr166 |
1.31 |
* in method {@link #onCompletion(CountedCompleter)}. As illustrated in the following |
258 |
dl |
1.1 |
* class (that performs a simplified form of map-reduce where mappings |
259 |
|
|
* and reductions are all of type {@code E}), one way to do this in |
260 |
|
|
* divide and conquer designs is to have each subtask record its |
261 |
|
|
* sibling, so that it can be accessed in method {@code onCompletion}. |
262 |
dl |
1.4 |
* This technique applies to reductions in which the order of |
263 |
|
|
* combining left and right results does not matter; ordered |
264 |
|
|
* reductions require explicit left/right designations. Variants of |
265 |
|
|
* other streamlinings seen in the above examples may also apply. |
266 |
dl |
1.1 |
* |
267 |
|
|
* <pre> {@code |
268 |
|
|
* class MyMapper<E> { E apply(E v) { ... } } |
269 |
|
|
* class MyReducer<E> { E apply(E x, E y) { ... } } |
270 |
dl |
1.4 |
* class MapReducer<E> extends CountedCompleter<E> { |
271 |
dl |
1.15 |
* final E[] array; final MyMapper<E> mapper; |
272 |
|
|
* final MyReducer<E> reducer; final int lo, hi; |
273 |
|
|
* MapReducer<E> sibling; |
274 |
|
|
* E result; |
275 |
|
|
* MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper, |
276 |
|
|
* MyReducer<E> reducer, int lo, int hi) { |
277 |
|
|
* super(p); |
278 |
|
|
* this.array = array; this.mapper = mapper; |
279 |
|
|
* this.reducer = reducer; this.lo = lo; this.hi = hi; |
280 |
|
|
* } |
281 |
|
|
* public void compute() { |
282 |
|
|
* if (hi - lo >= 2) { |
283 |
|
|
* int mid = (lo + hi) >>> 1; |
284 |
|
|
* MapReducer<E> left = new MapReducer(this, array, mapper, reducer, lo, mid); |
285 |
|
|
* MapReducer<E> right = new MapReducer(this, array, mapper, reducer, mid, hi); |
286 |
|
|
* left.sibling = right; |
287 |
|
|
* right.sibling = left; |
288 |
|
|
* setPendingCount(1); // only right is pending |
289 |
|
|
* right.fork(); |
290 |
|
|
* left.compute(); // directly execute left |
291 |
|
|
* } |
292 |
|
|
* else { |
293 |
|
|
* if (hi > lo) |
294 |
|
|
* result = mapper.apply(array[lo]); |
295 |
|
|
* tryComplete(); |
296 |
|
|
* } |
297 |
|
|
* } |
298 |
|
|
* public void onCompletion(CountedCompleter<?> caller) { |
299 |
|
|
* if (caller != this) { |
300 |
jsr166 |
1.23 |
* MapReducer<E> child = (MapReducer<E>)caller; |
301 |
|
|
* MapReducer<E> sib = child.sibling; |
302 |
|
|
* if (sib == null || sib.result == null) |
303 |
|
|
* result = child.result; |
304 |
|
|
* else |
305 |
|
|
* result = reducer.apply(child.result, sib.result); |
306 |
dl |
1.15 |
* } |
307 |
|
|
* } |
308 |
|
|
* public E getRawResult() { return result; } |
309 |
|
|
* |
310 |
|
|
* public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) { |
311 |
|
|
* return new MapReducer<E>(null, array, mapper, reducer, |
312 |
|
|
* 0, array.length).invoke(); |
313 |
|
|
* } |
314 |
jsr166 |
1.21 |
* }}</pre> |
315 |
dl |
1.1 |
* |
316 |
dl |
1.14 |
* Here, method {@code onCompletion} takes a form common to many |
317 |
|
|
* completion designs that combine results. This callback-style method |
318 |
|
|
* is triggered once per task, in either of the two different contexts |
319 |
|
|
* in which the pending count is, or becomes, zero: (1) by a task |
320 |
|
|
* itself, if its pending count is zero upon invocation of {@code |
321 |
|
|
* tryComplete}, or (2) by any of its subtasks when they complete and |
322 |
|
|
* decrement the pending count to zero. The {@code caller} argument |
323 |
|
|
* distinguishes cases. Most often, when the caller is {@code this}, |
324 |
|
|
* no action is necessary. Otherwise the caller argument can be used |
325 |
|
|
* (usually via a cast) to supply a value (and/or links to other |
326 |
jsr166 |
1.19 |
* values) to be combined. Assuming proper use of pending counts, the |
327 |
dl |
1.14 |
* actions inside {@code onCompletion} occur (once) upon completion of |
328 |
|
|
* a task and its subtasks. No additional synchronization is required |
329 |
|
|
* within this method to ensure thread safety of accesses to fields of |
330 |
|
|
* this task or other completed tasks. |
331 |
|
|
* |
332 |
dl |
1.15 |
* <p><b>Completion Traversals</b>. If using {@code onCompletion} to |
333 |
|
|
* process completions is inapplicable or inconvenient, you can use |
334 |
|
|
* methods {@link #firstComplete} and {@link #nextComplete} to create |
335 |
|
|
* custom traversals. For example, to define a MapReducer that only |
336 |
|
|
* splits out right-hand tasks in the form of the third ForEach |
337 |
|
|
* example, the completions must cooperatively reduce along |
338 |
|
|
* unexhausted subtask links, which can be done as follows: |
339 |
dl |
1.14 |
* |
340 |
|
|
* <pre> {@code |
341 |
dl |
1.15 |
* class MapReducer<E> extends CountedCompleter<E> { // version 2 |
342 |
|
|
* final E[] array; final MyMapper<E> mapper; |
343 |
|
|
* final MyReducer<E> reducer; final int lo, hi; |
344 |
|
|
* MapReducer<E> forks, next; // record subtask forks in list |
345 |
|
|
* E result; |
346 |
|
|
* MapReducer(CountedCompleter<?> p, E[] array, MyMapper<E> mapper, |
347 |
|
|
* MyReducer<E> reducer, int lo, int hi, MapReducer<E> next) { |
348 |
|
|
* super(p); |
349 |
|
|
* this.array = array; this.mapper = mapper; |
350 |
|
|
* this.reducer = reducer; this.lo = lo; this.hi = hi; |
351 |
|
|
* this.next = next; |
352 |
|
|
* } |
353 |
|
|
* public void compute() { |
354 |
jsr166 |
1.47 |
* int l = lo, h = hi; |
355 |
dl |
1.15 |
* while (h - l >= 2) { |
356 |
|
|
* int mid = (l + h) >>> 1; |
357 |
|
|
* addToPendingCount(1); |
358 |
dl |
1.29 |
* (forks = new MapReducer(this, array, mapper, reducer, mid, h, forks)).fork(); |
359 |
dl |
1.15 |
* h = mid; |
360 |
|
|
* } |
361 |
|
|
* if (h > l) |
362 |
|
|
* result = mapper.apply(array[l]); |
363 |
|
|
* // process completions by reducing along and advancing subtask links |
364 |
|
|
* for (CountedCompleter<?> c = firstComplete(); c != null; c = c.nextComplete()) { |
365 |
jsr166 |
1.47 |
* for (MapReducer t = (MapReducer)c, s = t.forks; s != null; s = t.forks = s.next) |
366 |
dl |
1.15 |
* t.result = reducer.apply(t.result, s.result); |
367 |
|
|
* } |
368 |
|
|
* } |
369 |
|
|
* public E getRawResult() { return result; } |
370 |
|
|
* |
371 |
|
|
* public static <E> E mapReduce(E[] array, MyMapper<E> mapper, MyReducer<E> reducer) { |
372 |
|
|
* return new MapReducer<E>(null, array, mapper, reducer, |
373 |
|
|
* 0, array.length, null).invoke(); |
374 |
|
|
* } |
375 |
|
|
* }}</pre> |
376 |
dl |
1.14 |
* |
377 |
dl |
1.1 |
* <p><b>Triggers.</b> Some CountedCompleters are themselves never |
378 |
|
|
* forked, but instead serve as bits of plumbing in other designs; |
379 |
jsr166 |
1.37 |
* including those in which the completion of one or more async tasks |
380 |
dl |
1.1 |
* triggers another async task. For example: |
381 |
|
|
* |
382 |
|
|
* <pre> {@code |
383 |
dl |
1.4 |
* class HeaderBuilder extends CountedCompleter<...> { ... } |
384 |
|
|
* class BodyBuilder extends CountedCompleter<...> { ... } |
385 |
|
|
* class PacketSender extends CountedCompleter<...> { |
386 |
dl |
1.15 |
* PacketSender(...) { super(null, 1); ... } // trigger on second completion |
387 |
|
|
* public void compute() { } // never called |
388 |
|
|
* public void onCompletion(CountedCompleter<?> caller) { sendPacket(); } |
389 |
dl |
1.1 |
* } |
390 |
|
|
* // sample use: |
391 |
|
|
* PacketSender p = new PacketSender(); |
392 |
|
|
* new HeaderBuilder(p, ...).fork(); |
393 |
jsr166 |
1.46 |
* new BodyBuilder(p, ...).fork();}</pre> |
394 |
dl |
1.1 |
* |
395 |
|
|
* @since 1.8 |
396 |
|
|
* @author Doug Lea |
397 |
|
|
*/ |
398 |
dl |
1.4 |
public abstract class CountedCompleter<T> extends ForkJoinTask<T> { |
399 |
dl |
1.2 |
private static final long serialVersionUID = 5232453752276485070L; |
400 |
|
|
|
401 |
dl |
1.1 |
/** This task's completer, or null if none */ |
402 |
dl |
1.4 |
final CountedCompleter<?> completer; |
403 |
dl |
1.1 |
/** The number of pending tasks until completion */ |
404 |
|
|
volatile int pending; |
405 |
|
|
|
406 |
|
|
/** |
407 |
|
|
* Creates a new CountedCompleter with the given completer |
408 |
|
|
* and initial pending count. |
409 |
|
|
* |
410 |
jsr166 |
1.24 |
* @param completer this task's completer, or {@code null} if none |
411 |
dl |
1.1 |
* @param initialPendingCount the initial pending count |
412 |
|
|
*/ |
413 |
dl |
1.4 |
protected CountedCompleter(CountedCompleter<?> completer, |
414 |
dl |
1.1 |
int initialPendingCount) { |
415 |
|
|
this.completer = completer; |
416 |
|
|
this.pending = initialPendingCount; |
417 |
|
|
} |
418 |
|
|
|
419 |
|
|
/** |
420 |
|
|
* Creates a new CountedCompleter with the given completer |
421 |
|
|
* and an initial pending count of zero. |
422 |
|
|
* |
423 |
jsr166 |
1.24 |
* @param completer this task's completer, or {@code null} if none |
424 |
dl |
1.1 |
*/ |
425 |
dl |
1.4 |
protected CountedCompleter(CountedCompleter<?> completer) { |
426 |
dl |
1.1 |
this.completer = completer; |
427 |
|
|
} |
428 |
|
|
|
429 |
|
|
/** |
430 |
|
|
* Creates a new CountedCompleter with no completer |
431 |
|
|
* and an initial pending count of zero. |
432 |
|
|
*/ |
433 |
|
|
protected CountedCompleter() { |
434 |
|
|
this.completer = null; |
435 |
|
|
} |
436 |
|
|
|
437 |
|
|
/** |
438 |
|
|
* The main computation performed by this task. |
439 |
|
|
*/ |
440 |
|
|
public abstract void compute(); |
441 |
|
|
|
442 |
|
|
/** |
443 |
dl |
1.2 |
* Performs an action when method {@link #tryComplete} is invoked |
444 |
jsr166 |
1.24 |
* and the pending count is zero, or when the unconditional |
445 |
dl |
1.2 |
* method {@link #complete} is invoked. By default, this method |
446 |
dl |
1.14 |
* does nothing. You can distinguish cases by checking the |
447 |
|
|
* identity of the given caller argument. If not equal to {@code |
448 |
|
|
* this}, then it is typically a subtask that may contain results |
449 |
|
|
* (and/or links to other results) to combine. |
450 |
dl |
1.1 |
* |
451 |
|
|
* @param caller the task invoking this method (which may |
452 |
jsr166 |
1.30 |
* be this task itself) |
453 |
dl |
1.1 |
*/ |
454 |
dl |
1.4 |
public void onCompletion(CountedCompleter<?> caller) { |
455 |
dl |
1.1 |
} |
456 |
|
|
|
457 |
|
|
/** |
458 |
dl |
1.36 |
* Performs an action when method {@link |
459 |
|
|
* #completeExceptionally(Throwable)} is invoked or method {@link |
460 |
jsr166 |
1.39 |
* #compute} throws an exception, and this task has not already |
461 |
|
|
* otherwise completed normally. On entry to this method, this task |
462 |
dl |
1.36 |
* {@link ForkJoinTask#isCompletedAbnormally}. The return value |
463 |
|
|
* of this method controls further propagation: If {@code true} |
464 |
|
|
* and this task has a completer that has not completed, then that |
465 |
|
|
* completer is also completed exceptionally, with the same |
466 |
|
|
* exception as this completer. The default implementation of |
467 |
|
|
* this method does nothing except return {@code true}. |
468 |
dl |
1.2 |
* |
469 |
|
|
* @param ex the exception |
470 |
|
|
* @param caller the task invoking this method (which may |
471 |
jsr166 |
1.30 |
* be this task itself) |
472 |
jsr166 |
1.33 |
* @return {@code true} if this exception should be propagated to this |
473 |
jsr166 |
1.30 |
* task's completer, if one exists |
474 |
dl |
1.2 |
*/ |
475 |
dl |
1.4 |
public boolean onExceptionalCompletion(Throwable ex, CountedCompleter<?> caller) { |
476 |
dl |
1.2 |
return true; |
477 |
|
|
} |
478 |
|
|
|
479 |
|
|
/** |
480 |
dl |
1.1 |
* Returns the completer established in this task's constructor, |
481 |
|
|
* or {@code null} if none. |
482 |
|
|
* |
483 |
|
|
* @return the completer |
484 |
|
|
*/ |
485 |
dl |
1.4 |
public final CountedCompleter<?> getCompleter() { |
486 |
dl |
1.1 |
return completer; |
487 |
|
|
} |
488 |
|
|
|
489 |
|
|
/** |
490 |
|
|
* Returns the current pending count. |
491 |
|
|
* |
492 |
|
|
* @return the current pending count |
493 |
|
|
*/ |
494 |
|
|
public final int getPendingCount() { |
495 |
|
|
return pending; |
496 |
|
|
} |
497 |
|
|
|
498 |
|
|
/** |
499 |
|
|
* Sets the pending count to the given value. |
500 |
|
|
* |
501 |
|
|
* @param count the count |
502 |
|
|
*/ |
503 |
|
|
public final void setPendingCount(int count) { |
504 |
|
|
pending = count; |
505 |
|
|
} |
506 |
|
|
|
507 |
|
|
/** |
508 |
|
|
* Adds (atomically) the given value to the pending count. |
509 |
|
|
* |
510 |
|
|
* @param delta the value to add |
511 |
|
|
*/ |
512 |
|
|
public final void addToPendingCount(int delta) { |
513 |
dl |
1.55 |
PENDING.getAndAdd(this, delta); |
514 |
dl |
1.1 |
} |
515 |
|
|
|
516 |
|
|
/** |
517 |
|
|
* Sets (atomically) the pending count to the given count only if |
518 |
|
|
* it currently holds the given expected value. |
519 |
|
|
* |
520 |
|
|
* @param expected the expected value |
521 |
|
|
* @param count the new value |
522 |
jsr166 |
1.33 |
* @return {@code true} if successful |
523 |
dl |
1.1 |
*/ |
524 |
|
|
public final boolean compareAndSetPendingCount(int expected, int count) { |
525 |
dl |
1.55 |
return PENDING.compareAndSet(this, expected, count); |
526 |
dl |
1.1 |
} |
527 |
|
|
|
528 |
|
|
/** |
529 |
dl |
1.15 |
* If the pending count is nonzero, (atomically) decrements it. |
530 |
|
|
* |
531 |
jsr166 |
1.16 |
* @return the initial (undecremented) pending count holding on entry |
532 |
dl |
1.15 |
* to this method |
533 |
|
|
*/ |
534 |
|
|
public final int decrementPendingCountUnlessZero() { |
535 |
|
|
int c; |
536 |
|
|
do {} while ((c = pending) != 0 && |
537 |
dl |
1.57 |
!PENDING.weakCompareAndSetVolatile(this, c, c - 1)); |
538 |
dl |
1.15 |
return c; |
539 |
|
|
} |
540 |
|
|
|
541 |
|
|
/** |
542 |
dl |
1.7 |
* Returns the root of the current computation; i.e., this |
543 |
|
|
* task if it has no completer, else its completer's root. |
544 |
|
|
* |
545 |
|
|
* @return the root of the current computation |
546 |
|
|
*/ |
547 |
|
|
public final CountedCompleter<?> getRoot() { |
548 |
|
|
CountedCompleter<?> a = this, p; |
549 |
|
|
while ((p = a.completer) != null) |
550 |
|
|
a = p; |
551 |
|
|
return a; |
552 |
|
|
} |
553 |
|
|
|
554 |
|
|
/** |
555 |
dl |
1.1 |
* If the pending count is nonzero, decrements the count; |
556 |
jsr166 |
1.31 |
* otherwise invokes {@link #onCompletion(CountedCompleter)} |
557 |
|
|
* and then similarly tries to complete this task's completer, |
558 |
|
|
* if one exists, else marks this task as complete. |
559 |
dl |
1.1 |
*/ |
560 |
|
|
public final void tryComplete() { |
561 |
dl |
1.4 |
CountedCompleter<?> a = this, s = a; |
562 |
dl |
1.2 |
for (int c;;) { |
563 |
dl |
1.1 |
if ((c = a.pending) == 0) { |
564 |
|
|
a.onCompletion(s); |
565 |
|
|
if ((a = (s = a).completer) == null) { |
566 |
|
|
s.quietlyComplete(); |
567 |
|
|
return; |
568 |
|
|
} |
569 |
|
|
} |
570 |
dl |
1.57 |
else if (PENDING.weakCompareAndSetVolatile(a, c, c - 1)) |
571 |
dl |
1.1 |
return; |
572 |
|
|
} |
573 |
|
|
} |
574 |
|
|
|
575 |
|
|
/** |
576 |
dl |
1.15 |
* Equivalent to {@link #tryComplete} but does not invoke {@link |
577 |
jsr166 |
1.31 |
* #onCompletion(CountedCompleter)} along the completion path: |
578 |
|
|
* If the pending count is nonzero, decrements the count; |
579 |
|
|
* otherwise, similarly tries to complete this task's completer, if |
580 |
|
|
* one exists, else marks this task as complete. This method may be |
581 |
|
|
* useful in cases where {@code onCompletion} should not, or need |
582 |
|
|
* not, be invoked for each completer in a computation. |
583 |
dl |
1.15 |
*/ |
584 |
|
|
public final void propagateCompletion() { |
585 |
jsr166 |
1.54 |
CountedCompleter<?> a = this, s; |
586 |
dl |
1.15 |
for (int c;;) { |
587 |
|
|
if ((c = a.pending) == 0) { |
588 |
|
|
if ((a = (s = a).completer) == null) { |
589 |
|
|
s.quietlyComplete(); |
590 |
|
|
return; |
591 |
|
|
} |
592 |
|
|
} |
593 |
dl |
1.57 |
else if (PENDING.weakCompareAndSetVolatile(a, c, c - 1)) |
594 |
dl |
1.15 |
return; |
595 |
|
|
} |
596 |
|
|
} |
597 |
|
|
|
598 |
|
|
/** |
599 |
jsr166 |
1.31 |
* Regardless of pending count, invokes |
600 |
|
|
* {@link #onCompletion(CountedCompleter)}, marks this task as |
601 |
|
|
* complete and further triggers {@link #tryComplete} on this |
602 |
|
|
* task's completer, if one exists. The given rawResult is |
603 |
|
|
* used as an argument to {@link #setRawResult} before invoking |
604 |
|
|
* {@link #onCompletion(CountedCompleter)} or marking this task |
605 |
|
|
* as complete; its value is meaningful only for classes |
606 |
jsr166 |
1.40 |
* overriding {@code setRawResult}. This method does not modify |
607 |
|
|
* the pending count. |
608 |
dl |
1.14 |
* |
609 |
|
|
* <p>This method may be useful when forcing completion as soon as |
610 |
|
|
* any one (versus all) of several subtask results are obtained. |
611 |
|
|
* However, in the common (and recommended) case in which {@code |
612 |
|
|
* setRawResult} is not overridden, this effect can be obtained |
613 |
jsr166 |
1.50 |
* more simply using {@link #quietlyCompleteRoot()}. |
614 |
dl |
1.1 |
* |
615 |
dl |
1.4 |
* @param rawResult the raw result |
616 |
dl |
1.1 |
*/ |
617 |
dl |
1.4 |
public void complete(T rawResult) { |
618 |
|
|
CountedCompleter<?> p; |
619 |
dl |
1.14 |
setRawResult(rawResult); |
620 |
dl |
1.1 |
onCompletion(this); |
621 |
|
|
quietlyComplete(); |
622 |
|
|
if ((p = completer) != null) |
623 |
|
|
p.tryComplete(); |
624 |
|
|
} |
625 |
|
|
|
626 |
dl |
1.15 |
/** |
627 |
|
|
* If this task's pending count is zero, returns this task; |
628 |
jsr166 |
1.51 |
* otherwise decrements its pending count and returns {@code null}. |
629 |
|
|
* This method is designed to be used with {@link #nextComplete} in |
630 |
|
|
* completion traversal loops. |
631 |
dl |
1.15 |
* |
632 |
|
|
* @return this task, if pending count was zero, else {@code null} |
633 |
|
|
*/ |
634 |
|
|
public final CountedCompleter<?> firstComplete() { |
635 |
|
|
for (int c;;) { |
636 |
|
|
if ((c = pending) == 0) |
637 |
|
|
return this; |
638 |
dl |
1.57 |
else if (PENDING.weakCompareAndSetVolatile(this, c, c - 1)) |
639 |
dl |
1.15 |
return null; |
640 |
|
|
} |
641 |
|
|
} |
642 |
|
|
|
643 |
|
|
/** |
644 |
|
|
* If this task does not have a completer, invokes {@link |
645 |
|
|
* ForkJoinTask#quietlyComplete} and returns {@code null}. Or, if |
646 |
dl |
1.29 |
* the completer's pending count is non-zero, decrements that |
647 |
|
|
* pending count and returns {@code null}. Otherwise, returns the |
648 |
dl |
1.15 |
* completer. This method can be used as part of a completion |
649 |
jsr166 |
1.18 |
* traversal loop for homogeneous task hierarchies: |
650 |
dl |
1.15 |
* |
651 |
|
|
* <pre> {@code |
652 |
jsr166 |
1.17 |
* for (CountedCompleter<?> c = firstComplete(); |
653 |
|
|
* c != null; |
654 |
|
|
* c = c.nextComplete()) { |
655 |
dl |
1.15 |
* // ... process c ... |
656 |
|
|
* }}</pre> |
657 |
|
|
* |
658 |
|
|
* @return the completer, or {@code null} if none |
659 |
|
|
*/ |
660 |
|
|
public final CountedCompleter<?> nextComplete() { |
661 |
|
|
CountedCompleter<?> p; |
662 |
|
|
if ((p = completer) != null) |
663 |
|
|
return p.firstComplete(); |
664 |
|
|
else { |
665 |
|
|
quietlyComplete(); |
666 |
|
|
return null; |
667 |
|
|
} |
668 |
|
|
} |
669 |
|
|
|
670 |
|
|
/** |
671 |
|
|
* Equivalent to {@code getRoot().quietlyComplete()}. |
672 |
|
|
*/ |
673 |
|
|
public final void quietlyCompleteRoot() { |
674 |
|
|
for (CountedCompleter<?> a = this, p;;) { |
675 |
|
|
if ((p = a.completer) == null) { |
676 |
|
|
a.quietlyComplete(); |
677 |
|
|
return; |
678 |
|
|
} |
679 |
|
|
a = p; |
680 |
|
|
} |
681 |
|
|
} |
682 |
|
|
|
683 |
dl |
1.1 |
/** |
684 |
dl |
1.42 |
* If this task has not completed, attempts to process at most the |
685 |
|
|
* given number of other unprocessed tasks for which this task is |
686 |
dl |
1.43 |
* on the completion path, if any are known to exist. |
687 |
dl |
1.42 |
* |
688 |
dl |
1.44 |
* @param maxTasks the maximum number of tasks to process. If |
689 |
|
|
* less than or equal to zero, then no tasks are |
690 |
|
|
* processed. |
691 |
dl |
1.42 |
*/ |
692 |
|
|
public final void helpComplete(int maxTasks) { |
693 |
|
|
Thread t; ForkJoinWorkerThread wt; |
694 |
|
|
if (maxTasks > 0 && status >= 0) { |
695 |
|
|
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) |
696 |
|
|
(wt = (ForkJoinWorkerThread)t).pool. |
697 |
|
|
helpComplete(wt.workQueue, this, maxTasks); |
698 |
|
|
else |
699 |
|
|
ForkJoinPool.common.externalHelpComplete(this, maxTasks); |
700 |
|
|
} |
701 |
|
|
} |
702 |
|
|
|
703 |
|
|
/** |
704 |
jsr166 |
1.22 |
* Supports ForkJoinTask exception propagation. |
705 |
dl |
1.2 |
*/ |
706 |
|
|
void internalPropagateException(Throwable ex) { |
707 |
dl |
1.4 |
CountedCompleter<?> a = this, s = a; |
708 |
dl |
1.2 |
while (a.onExceptionalCompletion(ex, s) && |
709 |
dl |
1.36 |
(a = (s = a).completer) != null && a.status >= 0 && |
710 |
|
|
a.recordExceptionalCompletion(ex) == EXCEPTIONAL) |
711 |
|
|
; |
712 |
dl |
1.2 |
} |
713 |
|
|
|
714 |
|
|
/** |
715 |
jsr166 |
1.22 |
* Implements execution conventions for CountedCompleters. |
716 |
dl |
1.1 |
*/ |
717 |
|
|
protected final boolean exec() { |
718 |
|
|
compute(); |
719 |
|
|
return false; |
720 |
|
|
} |
721 |
|
|
|
722 |
|
|
/** |
723 |
jsr166 |
1.45 |
* Returns the result of the computation. By default, |
724 |
dl |
1.4 |
* returns {@code null}, which is appropriate for {@code Void} |
725 |
dl |
1.15 |
* actions, but in other cases should be overridden, almost |
726 |
|
|
* always to return a field or function of a field that |
727 |
|
|
* holds the result upon completion. |
728 |
dl |
1.1 |
* |
729 |
dl |
1.4 |
* @return the result of the computation |
730 |
dl |
1.1 |
*/ |
731 |
dl |
1.4 |
public T getRawResult() { return null; } |
732 |
dl |
1.1 |
|
733 |
|
|
/** |
734 |
dl |
1.4 |
* A method that result-bearing CountedCompleters may optionally |
735 |
|
|
* use to help maintain result data. By default, does nothing. |
736 |
dl |
1.15 |
* Overrides are not recommended. However, if this method is |
737 |
|
|
* overridden to update existing objects or fields, then it must |
738 |
|
|
* in general be defined to be thread-safe. |
739 |
dl |
1.1 |
*/ |
740 |
dl |
1.4 |
protected void setRawResult(T t) { } |
741 |
dl |
1.1 |
|
742 |
dl |
1.55 |
// VarHandle mechanics |
743 |
|
|
private static final VarHandle PENDING; |
744 |
dl |
1.1 |
static { |
745 |
|
|
try { |
746 |
dl |
1.55 |
MethodHandles.Lookup l = MethodHandles.lookup(); |
747 |
|
|
PENDING = l.findVarHandle(CountedCompleter.class, "pending", int.class); |
748 |
jsr166 |
1.56 |
|
749 |
jsr166 |
1.48 |
} catch (ReflectiveOperationException e) { |
750 |
dl |
1.1 |
throw new Error(e); |
751 |
|
|
} |
752 |
|
|
} |
753 |
|
|
} |