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