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.io.Serializable; |
10 |
import java.lang.invoke.MethodHandles; |
11 |
import java.lang.invoke.VarHandle; |
12 |
import java.lang.ref.ReferenceQueue; |
13 |
import java.lang.ref.WeakReference; |
14 |
import java.lang.reflect.Constructor; |
15 |
import java.util.Collection; |
16 |
import java.util.List; |
17 |
import java.util.RandomAccess; |
18 |
import java.util.concurrent.locks.LockSupport; |
19 |
|
20 |
/** |
21 |
* Abstract base class for tasks that run within a {@link ForkJoinPool}. |
22 |
* A {@code ForkJoinTask} is a thread-like entity that is much |
23 |
* lighter weight than a normal thread. Huge numbers of tasks and |
24 |
* subtasks may be hosted by a small number of actual threads in a |
25 |
* ForkJoinPool, at the price of some usage limitations. |
26 |
* |
27 |
* <p>A "main" {@code ForkJoinTask} begins execution when it is |
28 |
* explicitly submitted to a {@link ForkJoinPool}, or, if not already |
29 |
* engaged in a ForkJoin computation, commenced in the {@link |
30 |
* ForkJoinPool#commonPool()} via {@link #fork}, {@link #invoke}, or |
31 |
* related methods. Once started, it will usually in turn start other |
32 |
* subtasks. As indicated by the name of this class, many programs |
33 |
* using {@code ForkJoinTask} employ only methods {@link #fork} and |
34 |
* {@link #join}, or derivatives such as {@link |
35 |
* #invokeAll(ForkJoinTask...) invokeAll}. However, this class also |
36 |
* provides a number of other methods that can come into play in |
37 |
* advanced usages, as well as extension mechanics that allow support |
38 |
* of new forms of fork/join processing. |
39 |
* |
40 |
* <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}. |
41 |
* The efficiency of {@code ForkJoinTask}s stems from a set of |
42 |
* restrictions (that are only partially statically enforceable) |
43 |
* reflecting their main use as computational tasks calculating pure |
44 |
* functions or operating on purely isolated objects. The primary |
45 |
* coordination mechanisms are {@link #fork}, that arranges |
46 |
* asynchronous execution, and {@link #join}, that doesn't proceed |
47 |
* until the task's result has been computed. Computations should |
48 |
* ideally avoid {@code synchronized} methods or blocks, and should |
49 |
* minimize other blocking synchronization apart from joining other |
50 |
* tasks or using synchronizers such as Phasers that are advertised to |
51 |
* cooperate with fork/join scheduling. Subdividable tasks should also |
52 |
* not perform blocking I/O, and should ideally access variables that |
53 |
* are completely independent of those accessed by other running |
54 |
* tasks. These guidelines are loosely enforced by not permitting |
55 |
* checked exceptions such as {@code IOExceptions} to be |
56 |
* thrown. However, computations may still encounter unchecked |
57 |
* exceptions, that are rethrown to callers attempting to join |
58 |
* them. These exceptions may additionally include {@link |
59 |
* RejectedExecutionException} stemming from internal resource |
60 |
* exhaustion, such as failure to allocate internal task |
61 |
* queues. Rethrown exceptions behave in the same way as regular |
62 |
* exceptions, but, when possible, contain stack traces (as displayed |
63 |
* for example using {@code ex.printStackTrace()}) of both the thread |
64 |
* that initiated the computation as well as the thread actually |
65 |
* encountering the exception; minimally only the latter. |
66 |
* |
67 |
* <p>It is possible to define and use ForkJoinTasks that may block, |
68 |
* but doing so requires three further considerations: (1) Completion |
69 |
* of few if any <em>other</em> tasks should be dependent on a task |
70 |
* that blocks on external synchronization or I/O. Event-style async |
71 |
* tasks that are never joined (for example, those subclassing {@link |
72 |
* CountedCompleter}) often fall into this category. (2) To minimize |
73 |
* resource impact, tasks should be small; ideally performing only the |
74 |
* (possibly) blocking action. (3) Unless the {@link |
75 |
* ForkJoinPool.ManagedBlocker} API is used, or the number of possibly |
76 |
* blocked tasks is known to be less than the pool's {@link |
77 |
* ForkJoinPool#getParallelism} level, the pool cannot guarantee that |
78 |
* enough threads will be available to ensure progress or good |
79 |
* performance. |
80 |
* |
81 |
* <p>The primary method for awaiting completion and extracting |
82 |
* results of a task is {@link #join}, but there are several variants: |
83 |
* The {@link Future#get} methods support interruptible and/or timed |
84 |
* waits for completion and report results using {@code Future} |
85 |
* conventions. Method {@link #invoke} is semantically |
86 |
* equivalent to {@code fork(); join()} but always attempts to begin |
87 |
* execution in the current thread. The "<em>quiet</em>" forms of |
88 |
* these methods do not extract results or report exceptions. These |
89 |
* may be useful when a set of tasks are being executed, and you need |
90 |
* to delay processing of results or exceptions until all complete. |
91 |
* Method {@code invokeAll} (available in multiple versions) |
92 |
* performs the most common form of parallel invocation: forking a set |
93 |
* of tasks and joining them all. |
94 |
* |
95 |
* <p>In the most typical usages, a fork-join pair act like a call |
96 |
* (fork) and return (join) from a parallel recursive function. As is |
97 |
* the case with other forms of recursive calls, returns (joins) |
98 |
* should be performed innermost-first. For example, {@code a.fork(); |
99 |
* b.fork(); b.join(); a.join();} is likely to be substantially more |
100 |
* efficient than joining {@code a} before {@code b}. |
101 |
* |
102 |
* <p>The execution status of tasks may be queried at several levels |
103 |
* of detail: {@link #isDone} is true if a task completed in any way |
104 |
* (including the case where a task was cancelled without executing); |
105 |
* {@link #isCompletedNormally} is true if a task completed without |
106 |
* cancellation or encountering an exception; {@link #isCancelled} is |
107 |
* true if the task was cancelled (in which case {@link #getException} |
108 |
* returns a {@link CancellationException}); and |
109 |
* {@link #isCompletedAbnormally} is true if a task was either |
110 |
* cancelled or encountered an exception, in which case {@link |
111 |
* #getException} will return either the encountered exception or |
112 |
* {@link CancellationException}. |
113 |
* |
114 |
* <p>The ForkJoinTask class is not usually directly subclassed. |
115 |
* Instead, you subclass one of the abstract classes that support a |
116 |
* particular style of fork/join processing, typically {@link |
117 |
* RecursiveAction} for most computations that do not return results, |
118 |
* {@link RecursiveTask} for those that do, and {@link |
119 |
* CountedCompleter} for those in which completed actions trigger |
120 |
* other actions. Normally, a concrete ForkJoinTask subclass declares |
121 |
* fields comprising its parameters, established in a constructor, and |
122 |
* then defines a {@code compute} method that somehow uses the control |
123 |
* methods supplied by this base class. |
124 |
* |
125 |
* <p>Method {@link #join} and its variants are appropriate for use |
126 |
* only when completion dependencies are acyclic; that is, the |
127 |
* parallel computation can be described as a directed acyclic graph |
128 |
* (DAG). Otherwise, executions may encounter a form of deadlock as |
129 |
* tasks cyclically wait for each other. However, this framework |
130 |
* supports other methods and techniques (for example the use of |
131 |
* {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that |
132 |
* may be of use in constructing custom subclasses for problems that |
133 |
* are not statically structured as DAGs. To support such usages, a |
134 |
* ForkJoinTask may be atomically <em>tagged</em> with a {@code short} |
135 |
* value using {@link #setForkJoinTaskTag} or {@link |
136 |
* #compareAndSetForkJoinTaskTag} and checked using {@link |
137 |
* #getForkJoinTaskTag}. The ForkJoinTask implementation does not use |
138 |
* these {@code protected} methods or tags for any purpose, but they |
139 |
* may be of use in the construction of specialized subclasses. For |
140 |
* example, parallel graph traversals can use the supplied methods to |
141 |
* avoid revisiting nodes/tasks that have already been processed. |
142 |
* (Method names for tagging are bulky in part to encourage definition |
143 |
* of methods that reflect their usage patterns.) |
144 |
* |
145 |
* <p>Most base support methods are {@code final}, to prevent |
146 |
* overriding of implementations that are intrinsically tied to the |
147 |
* underlying lightweight task scheduling framework. Developers |
148 |
* creating new basic styles of fork/join processing should minimally |
149 |
* implement {@code protected} methods {@link #exec}, {@link |
150 |
* #setRawResult}, and {@link #getRawResult}, while also introducing |
151 |
* an abstract computational method that can be implemented in its |
152 |
* subclasses, possibly relying on other {@code protected} methods |
153 |
* provided by this class. |
154 |
* |
155 |
* <p>ForkJoinTasks should perform relatively small amounts of |
156 |
* computation. Large tasks should be split into smaller subtasks, |
157 |
* usually via recursive decomposition. As a very rough rule of thumb, |
158 |
* a task should perform more than 100 and less than 10000 basic |
159 |
* computational steps, and should avoid indefinite looping. If tasks |
160 |
* are too big, then parallelism cannot improve throughput. If too |
161 |
* small, then memory and internal task maintenance overhead may |
162 |
* overwhelm processing. |
163 |
* |
164 |
* <p>This class provides {@code adapt} methods for {@link Runnable} |
165 |
* and {@link Callable}, that may be of use when mixing execution of |
166 |
* {@code ForkJoinTasks} with other kinds of tasks. When all tasks are |
167 |
* of this form, consider using a pool constructed in <em>asyncMode</em>. |
168 |
* |
169 |
* <p>ForkJoinTasks are {@code Serializable}, which enables them to be |
170 |
* used in extensions such as remote execution frameworks. It is |
171 |
* sensible to serialize tasks only before or after, but not during, |
172 |
* execution. Serialization is not relied on during execution itself. |
173 |
* |
174 |
* @since 1.7 |
175 |
* @author Doug Lea |
176 |
*/ |
177 |
public abstract class ForkJoinTask<V> implements Future<V>, Serializable { |
178 |
|
179 |
/* |
180 |
* See the internal documentation of class ForkJoinPool for a |
181 |
* general implementation overview. ForkJoinTasks are mainly |
182 |
* responsible for maintaining their "status" field amidst relays |
183 |
* to methods in ForkJoinWorkerThread and ForkJoinPool. |
184 |
* |
185 |
* The methods of this class are more-or-less layered into |
186 |
* (1) basic status maintenance |
187 |
* (2) execution and awaiting completion |
188 |
* (3) user-level methods that additionally report results. |
189 |
* This is sometimes hard to see because this file orders exported |
190 |
* methods in a way that flows well in javadocs. |
191 |
* |
192 |
* Revision notes: The use of "Aux" field replaces previous |
193 |
* reliance on a table to hold exceptions and synchronized blocks |
194 |
* and monitors to wait for completion. |
195 |
*/ |
196 |
|
197 |
/** |
198 |
* Nodes for threads waiting for completion, or holding a thrown |
199 |
* exception (never both). Waiting threads prepend nodes |
200 |
* Treiber-stack-style. Signallers detach and unpark |
201 |
* waiters. Cancelled waiters try to unsplice. |
202 |
*/ |
203 |
static final class Aux { |
204 |
final Thread thread; |
205 |
final Throwable ex; // null if a waiter |
206 |
Aux next; // accessed only via memory-acquire chains |
207 |
Aux(Thread thread, Throwable ex) { |
208 |
this.thread = thread; |
209 |
this.ex = ex; |
210 |
} |
211 |
final boolean casNext(Aux c, Aux v) { // used only in cancellation |
212 |
return NEXT.compareAndSet(this, c, v); |
213 |
} |
214 |
private static final VarHandle NEXT; |
215 |
static { |
216 |
try { |
217 |
NEXT = MethodHandles.lookup() |
218 |
.findVarHandle(Aux.class, "next", Aux.class); |
219 |
} catch (ReflectiveOperationException e) { |
220 |
throw new ExceptionInInitializerError(e); |
221 |
} |
222 |
} |
223 |
} |
224 |
|
225 |
/* |
226 |
* The status field holds bits packed into a single int to ensure |
227 |
* atomicity. Status is initially zero, and takes on nonnegative |
228 |
* values until completed, upon which it holds (sign bit) DONE, |
229 |
* possibly with ABNORMAL (cancelled or exceptional) and THROWN |
230 |
* (in which case an exception has been stored). These control |
231 |
* bits occupy only (some of) the upper half (16 bits) of status |
232 |
* field. The lower bits are used for user-defined tags. |
233 |
*/ |
234 |
private static final int DONE = 1 << 31; // must be negative |
235 |
private static final int ABNORMAL = 1 << 16; // set atomically with DONE |
236 |
private static final int THROWN = 1 << 17; // set atomically with ABNORMAL |
237 |
private static final int SMASK = 0xffff; // short bits for tags |
238 |
// sentinels can be any positive upper half value: |
239 |
private static final int INTRPT = 1 << 16; // awaitDone interrupt return |
240 |
static final int ADJUST = 1 << 16; // uncompensate after block |
241 |
|
242 |
// Fields |
243 |
volatile int status; // accessed directly by pool and workers |
244 |
private transient volatile Aux aux; // either waiters or thrown Exception |
245 |
// Support for atomic operations |
246 |
private static final VarHandle STATUS; |
247 |
private static final VarHandle AUX; |
248 |
private int getAndBitwiseOrStatus(int v) { |
249 |
return (int)STATUS.getAndBitwiseOr(this, v); |
250 |
} |
251 |
private boolean casStatus(int c, int v) { |
252 |
return STATUS.weakCompareAndSet(this, c, v); |
253 |
} |
254 |
private boolean casAux(Aux c, Aux v) { |
255 |
return AUX.compareAndSet(this, c, v); |
256 |
} |
257 |
|
258 |
/** Removes and unparks waiters */ |
259 |
private void signalWaiters() { |
260 |
for (Aux a; (a = aux) != null && a.ex == null; ) { |
261 |
if (casAux(a, null)) { // detach entire list |
262 |
for (Thread t; a != null; a = a.next) { |
263 |
if ((t = a.thread) != Thread.currentThread() && t != null) |
264 |
LockSupport.unpark(t); // don't self-signal |
265 |
} |
266 |
break; |
267 |
} |
268 |
} |
269 |
} |
270 |
|
271 |
/** |
272 |
* Possibly blocks until task is done or interrupted or timed out. |
273 |
* |
274 |
* @param interruptible true if wait can be cancelled by interrupt |
275 |
* @param deadline if non-zero use timed waits and possibly timeout |
276 |
* @param pool if nonull, pool to uncompensate when unblocking |
277 |
* @return status on exit, or INTRPT if interrupted while waiting |
278 |
*/ |
279 |
final int awaitDone(boolean interruptible, long deadline, |
280 |
ForkJoinPool pool) { |
281 |
int s; Aux node = null; boolean interrupted = false, queued = false; |
282 |
for (;;) { |
283 |
Aux a; long nanos; |
284 |
if ((s = status) < 0) |
285 |
break; |
286 |
else if (node == null) |
287 |
node = new Aux(Thread.currentThread(), null); |
288 |
else if (!queued) { |
289 |
if ((a = aux) != null && a.ex != null) |
290 |
Thread.onSpinWait(); // exception in progress |
291 |
else if (queued = casAux(node.next = a, node)) |
292 |
LockSupport.setCurrentBlocker(this); |
293 |
} |
294 |
else { |
295 |
if (deadline == 0L) |
296 |
LockSupport.park(); |
297 |
else if ((nanos = deadline - System.nanoTime()) > 0L) |
298 |
LockSupport.parkNanos(nanos); |
299 |
else { |
300 |
s = 0; // timeout |
301 |
break; |
302 |
} |
303 |
if ((interrupted |= Thread.interrupted()) && interruptible) { |
304 |
s = INTRPT; |
305 |
break; |
306 |
} |
307 |
} |
308 |
} |
309 |
if (pool != null) |
310 |
pool.uncompensate(); |
311 |
if (s >= 0) { // try to unsplice after cancellation |
312 |
outer: for (Aux a; (a = aux) != null && a.ex == null; ) { |
313 |
for (Aux trail = null;;) { |
314 |
Aux next = a.next; |
315 |
if (a == node) { |
316 |
if (trail != null) |
317 |
trail.casNext(trail, next); |
318 |
else if (casAux(a, next)) |
319 |
break outer; // cannot be re-encountered |
320 |
break; // restart |
321 |
} else { |
322 |
trail = a; |
323 |
if ((a = next) == null) |
324 |
break outer; |
325 |
} |
326 |
} |
327 |
} |
328 |
} |
329 |
else if (interrupted) |
330 |
Thread.currentThread().interrupt(); |
331 |
if (queued) { |
332 |
LockSupport.setCurrentBlocker(null); |
333 |
signalWaiters(); // help clean or signal |
334 |
} |
335 |
return s; |
336 |
} |
337 |
|
338 |
/** |
339 |
* Sets DONE status and wakes up threads waiting to join this task. |
340 |
* @return status on exit |
341 |
*/ |
342 |
private int setDone() { |
343 |
int s = getAndBitwiseOrStatus(DONE) | DONE; |
344 |
signalWaiters(); |
345 |
return s; |
346 |
} |
347 |
|
348 |
/** |
349 |
* Sets ABNORMAL DONE status unless already done, and wakes up threads |
350 |
* waiting to join this task. |
351 |
* @return status on exit |
352 |
*/ |
353 |
private int trySetCancelled() { |
354 |
int s; |
355 |
do {} while ((s = status) >= 0 && !casStatus(s, s |= (DONE | ABNORMAL))); |
356 |
signalWaiters(); |
357 |
return s; |
358 |
} |
359 |
|
360 |
/** |
361 |
* Records exception and sets ABNORMAL THROWN DONE status unless |
362 |
* already done, and wakes up threads waiting to join this task. |
363 |
* If losing a race with setDone or trySetCancelled, the exception |
364 |
* may be recorded but not reported. |
365 |
* |
366 |
* @return status on exit |
367 |
*/ |
368 |
final int trySetThrown(Throwable ex) { |
369 |
Aux h = new Aux(Thread.currentThread(), ex), p = null; |
370 |
boolean installed = false; |
371 |
int s; |
372 |
while ((s = status) >= 0) { |
373 |
Aux a; |
374 |
if (!installed && ((a = aux) == null || a.ex == null) && |
375 |
(installed = casAux(a, h))) |
376 |
p = a; // list of waiters replaced by h |
377 |
if (installed && casStatus(s, s |= (DONE | ABNORMAL | THROWN))) |
378 |
break; |
379 |
} |
380 |
for (; p != null; p = p.next) |
381 |
LockSupport.unpark(p.thread); |
382 |
return s; |
383 |
} |
384 |
|
385 |
/** |
386 |
* Records exception unless already done. Overridable in subclasses. |
387 |
* |
388 |
* @return status on exit |
389 |
*/ |
390 |
int trySetException(Throwable ex) { |
391 |
return trySetThrown(ex); |
392 |
} |
393 |
|
394 |
static boolean isExceptionalStatus(int s) { // needed by subclasses |
395 |
return (s & THROWN) != 0; |
396 |
} |
397 |
|
398 |
/** |
399 |
* Unless done, calls exec and records status if completed, but |
400 |
* doesn't wait for completion otherwise. |
401 |
* |
402 |
* @return status on exit from this method |
403 |
*/ |
404 |
final int doExec() { |
405 |
int s; boolean completed; |
406 |
if ((s = status) >= 0) { |
407 |
try { |
408 |
completed = exec(); |
409 |
} catch (Throwable rex) { |
410 |
s = trySetException(rex); |
411 |
completed = false; |
412 |
} |
413 |
if (completed) |
414 |
s = setDone(); |
415 |
} |
416 |
return s; |
417 |
} |
418 |
|
419 |
/** |
420 |
* Helps and/or waits for completion. Overridable in subclasses. |
421 |
* |
422 |
* @param interruptible true if wait can be cancelled by interrupt |
423 |
* @param ran true if task known to be invoked |
424 |
* @return status on exit, or INTRPT if interruptible and interrupted |
425 |
*/ |
426 |
int awaitJoin(boolean interruptible, boolean ran) { |
427 |
Thread t; ForkJoinWorkerThread wt; |
428 |
ForkJoinPool.WorkQueue q = null; |
429 |
ForkJoinPool p = null; |
430 |
boolean unforked = false; |
431 |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) { |
432 |
p = (wt = (ForkJoinWorkerThread)t).pool; |
433 |
q = wt.workQueue; |
434 |
if (!ran && q != null && q.tryRemove(this)) |
435 |
unforked = true; |
436 |
} |
437 |
else if (!ran && (q = ForkJoinPool.commonQueue()) != null && |
438 |
q.externalTryUnpush(this)) |
439 |
unforked = true; |
440 |
int s; |
441 |
if (unforked && (s = doExec()) < 0) |
442 |
return s; |
443 |
if (p != null) { |
444 |
if ((s = p.helpJoin(this, q)) < 0) |
445 |
return s; |
446 |
if (s != ADJUST) // uncompensated |
447 |
p = null; |
448 |
} |
449 |
return awaitDone(interruptible, 0L, p); |
450 |
} |
451 |
|
452 |
/** |
453 |
* Cancels, ignoring any exceptions thrown by cancel. Used during |
454 |
* worker and pool shutdown. Cancel is spec'ed not to throw any |
455 |
* exceptions, but if it does anyway, we have no recourse during |
456 |
* shutdown, so guard against this case. |
457 |
*/ |
458 |
static final void cancelIgnoringExceptions(ForkJoinTask<?> t) { |
459 |
if (t != null) { |
460 |
try { |
461 |
t.cancel(false); |
462 |
} catch (Throwable ignore) { |
463 |
} |
464 |
} |
465 |
} |
466 |
|
467 |
/** |
468 |
* Returns a rethrowable exception for this task, if available. |
469 |
* To provide accurate stack traces, if the exception was not |
470 |
* thrown by the current thread, we try to create a new exception |
471 |
* of the same type as the one thrown, but with the recorded |
472 |
* exception as its cause. If there is no such constructor, we |
473 |
* instead try to use a no-arg constructor, followed by initCause, |
474 |
* to the same effect. If none of these apply, or any fail due to |
475 |
* other exceptions, we return the recorded exception, which is |
476 |
* still correct, although it may contain a misleading stack |
477 |
* trace. |
478 |
* |
479 |
* @return the exception, or null if none |
480 |
*/ |
481 |
private Throwable getThrowableException() { |
482 |
Throwable ex; Aux a; |
483 |
if ((a = aux) == null) |
484 |
ex = null; |
485 |
else if ((ex = a.ex) != null && a.thread != Thread.currentThread()) { |
486 |
try { |
487 |
Constructor<?> noArgCtor = null, oneArgCtor = null; |
488 |
for (Constructor<?> c : ex.getClass().getConstructors()) { |
489 |
Class<?>[] ps = c.getParameterTypes(); |
490 |
if (ps.length == 0) |
491 |
noArgCtor = c; |
492 |
else if (ps.length == 1 && ps[0] == Throwable.class) { |
493 |
oneArgCtor = c; |
494 |
break; |
495 |
} |
496 |
} |
497 |
if (oneArgCtor != null) |
498 |
ex = (Throwable)oneArgCtor.newInstance(ex); |
499 |
else if (noArgCtor != null) { |
500 |
Throwable rx = (Throwable)noArgCtor.newInstance(); |
501 |
rx.initCause(ex); |
502 |
ex = rx; |
503 |
} |
504 |
} catch (Exception ignore) { |
505 |
} |
506 |
} |
507 |
return ex; |
508 |
} |
509 |
|
510 |
/** |
511 |
* Throws exception associated with the given status, or |
512 |
* CancellationException if none recorded. |
513 |
*/ |
514 |
private void reportException(int s) { |
515 |
ForkJoinTask.<RuntimeException>uncheckedThrow( |
516 |
(s & THROWN) != 0 ? getThrowableException() : null); |
517 |
} |
518 |
|
519 |
/** |
520 |
* A version of "sneaky throw" to relay exceptions in other |
521 |
* contexts. |
522 |
*/ |
523 |
static void rethrow(Throwable ex) { |
524 |
ForkJoinTask.<RuntimeException>uncheckedThrow(ex); |
525 |
} |
526 |
|
527 |
/** |
528 |
* The sneaky part of sneaky throw, relying on generics |
529 |
* limitations to evade compiler complaints about rethrowing |
530 |
* unchecked exceptions. If argument null, throws |
531 |
* CancellationException. |
532 |
*/ |
533 |
@SuppressWarnings("unchecked") static <T extends Throwable> |
534 |
void uncheckedThrow(Throwable t) throws T { |
535 |
if (t == null) |
536 |
t = new CancellationException(); |
537 |
throw (T)t; // rely on vacuous cast |
538 |
} |
539 |
|
540 |
// public methods |
541 |
|
542 |
/** |
543 |
* Arranges to asynchronously execute this task in the pool the |
544 |
* current task is running in, if applicable, or using the {@link |
545 |
* ForkJoinPool#commonPool()} if not {@link #inForkJoinPool}. While |
546 |
* it is not necessarily enforced, it is a usage error to fork a |
547 |
* task more than once unless it has completed and been |
548 |
* reinitialized. Subsequent modifications to the state of this |
549 |
* task or any data it operates on are not necessarily |
550 |
* consistently observable by any thread other than the one |
551 |
* executing it unless preceded by a call to {@link #join} or |
552 |
* related methods, or a call to {@link #isDone} returning {@code |
553 |
* true}. |
554 |
* |
555 |
* @return {@code this}, to simplify usage |
556 |
*/ |
557 |
public final ForkJoinTask<V> fork() { |
558 |
Thread t; ForkJoinWorkerThread w; |
559 |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) |
560 |
(w = (ForkJoinWorkerThread)t).workQueue.push(this, w.pool); |
561 |
else |
562 |
ForkJoinPool.common.externalPush(this); |
563 |
return this; |
564 |
} |
565 |
|
566 |
/** |
567 |
* Returns the result of the computation when it |
568 |
* {@linkplain #isDone is done}. |
569 |
* This method differs from {@link #get()} in that abnormal |
570 |
* completion results in {@code RuntimeException} or {@code Error}, |
571 |
* not {@code ExecutionException}, and that interrupts of the |
572 |
* calling thread do <em>not</em> cause the method to abruptly |
573 |
* return by throwing {@code InterruptedException}. |
574 |
* |
575 |
* @return the computed result |
576 |
*/ |
577 |
public final V join() { |
578 |
int s; |
579 |
if ((s = status) >= 0) |
580 |
s = awaitJoin(false, false); |
581 |
if ((s & ABNORMAL) != 0) |
582 |
reportException(s); |
583 |
return getRawResult(); |
584 |
} |
585 |
|
586 |
/** |
587 |
* Commences performing this task, awaits its completion if |
588 |
* necessary, and returns its result, or throws an (unchecked) |
589 |
* {@code RuntimeException} or {@code Error} if the underlying |
590 |
* computation did so. |
591 |
* |
592 |
* @return the computed result |
593 |
*/ |
594 |
public final V invoke() { |
595 |
int s; |
596 |
if ((s = doExec()) >= 0) |
597 |
s = awaitJoin(false, true); |
598 |
if ((s & ABNORMAL) != 0) |
599 |
reportException(s); |
600 |
return getRawResult(); |
601 |
} |
602 |
|
603 |
/** |
604 |
* Forks the given tasks, returning when {@code isDone} holds for |
605 |
* each task or an (unchecked) exception is encountered, in which |
606 |
* case the exception is rethrown. If more than one task |
607 |
* encounters an exception, then this method throws any one of |
608 |
* these exceptions. If any task encounters an exception, the |
609 |
* other may be cancelled. However, the execution status of |
610 |
* individual tasks is not guaranteed upon exceptional return. The |
611 |
* status of each task may be obtained using {@link |
612 |
* #getException()} and related methods to check if they have been |
613 |
* cancelled, completed normally or exceptionally, or left |
614 |
* unprocessed. |
615 |
* |
616 |
* @param t1 the first task |
617 |
* @param t2 the second task |
618 |
* @throws NullPointerException if any task is null |
619 |
*/ |
620 |
public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) { |
621 |
int s1, s2; |
622 |
if (t1 == null || t2 == null) |
623 |
throw new NullPointerException(); |
624 |
t2.fork(); |
625 |
if ((s1 = t1.doExec()) >= 0) |
626 |
s1 = t1.awaitJoin(false, true); |
627 |
if ((s1 & ABNORMAL) != 0) { |
628 |
t2.cancel(false); |
629 |
t1.reportException(s1); |
630 |
} |
631 |
else { |
632 |
if ((s2 = t2.status) >= 0) |
633 |
s2 = t2.awaitJoin(false, false); |
634 |
if ((s2 & ABNORMAL) != 0) |
635 |
t2.reportException(s2); |
636 |
} |
637 |
} |
638 |
|
639 |
/** |
640 |
* Forks the given tasks, returning when {@code isDone} holds for |
641 |
* each task or an (unchecked) exception is encountered, in which |
642 |
* case the exception is rethrown. If more than one task |
643 |
* encounters an exception, then this method throws any one of |
644 |
* these exceptions. If any task encounters an exception, others |
645 |
* may be cancelled. However, the execution status of individual |
646 |
* tasks is not guaranteed upon exceptional return. The status of |
647 |
* each task may be obtained using {@link #getException()} and |
648 |
* related methods to check if they have been cancelled, completed |
649 |
* normally or exceptionally, or left unprocessed. |
650 |
* |
651 |
* @param tasks the tasks |
652 |
* @throws NullPointerException if any task is null |
653 |
*/ |
654 |
public static void invokeAll(ForkJoinTask<?>... tasks) { |
655 |
Throwable ex = null; |
656 |
int last = tasks.length - 1; |
657 |
for (int i = last, s; i >= 0; --i) { |
658 |
ForkJoinTask<?> t; |
659 |
if ((t = tasks[i]) == null) { |
660 |
ex = new NullPointerException(); |
661 |
break; |
662 |
} |
663 |
if (i == 0) { |
664 |
if ((s = t.doExec()) >= 0) |
665 |
s = t.awaitJoin(false, true); |
666 |
if ((s & ABNORMAL) != 0) |
667 |
ex = t.getException(); |
668 |
break; |
669 |
} |
670 |
t.fork(); |
671 |
} |
672 |
if (ex == null) { |
673 |
for (int i = 1, s; i <= last; ++i) { |
674 |
ForkJoinTask<?> t; |
675 |
if ((t = tasks[i]) != null) { |
676 |
if ((s = t.status) >= 0) |
677 |
s = t.awaitJoin(false, false); |
678 |
if ((s & ABNORMAL) != 0) { |
679 |
ex = t.getException(); |
680 |
break; |
681 |
} |
682 |
} |
683 |
} |
684 |
} |
685 |
if (ex != null) { // try to cancel others |
686 |
for (int i = 0, s; i <= last; ++i) { |
687 |
ForkJoinTask<?> t; |
688 |
if ((t = tasks[i]) != null) |
689 |
t.cancel(false); |
690 |
} |
691 |
rethrow(ex); |
692 |
} |
693 |
} |
694 |
|
695 |
/** |
696 |
* Forks all tasks in the specified collection, returning when |
697 |
* {@code isDone} holds for each task or an (unchecked) exception |
698 |
* is encountered, in which case the exception is rethrown. If |
699 |
* more than one task encounters an exception, then this method |
700 |
* throws any one of these exceptions. If any task encounters an |
701 |
* exception, others may be cancelled. However, the execution |
702 |
* status of individual tasks is not guaranteed upon exceptional |
703 |
* return. The status of each task may be obtained using {@link |
704 |
* #getException()} and related methods to check if they have been |
705 |
* cancelled, completed normally or exceptionally, or left |
706 |
* unprocessed. |
707 |
* |
708 |
* @param tasks the collection of tasks |
709 |
* @param <T> the type of the values returned from the tasks |
710 |
* @return the tasks argument, to simplify usage |
711 |
* @throws NullPointerException if tasks or any element are null |
712 |
*/ |
713 |
public static <T extends ForkJoinTask<?>> Collection<T> invokeAll(Collection<T> tasks) { |
714 |
if (!(tasks instanceof RandomAccess) || !(tasks instanceof List<?>)) { |
715 |
invokeAll(tasks.toArray(new ForkJoinTask<?>[0])); |
716 |
return tasks; |
717 |
} |
718 |
@SuppressWarnings("unchecked") |
719 |
List<? extends ForkJoinTask<?>> ts = |
720 |
(List<? extends ForkJoinTask<?>>) tasks; |
721 |
Throwable ex = null; |
722 |
int last = ts.size() - 1; // nearly same as array version |
723 |
for (int i = last, s; i >= 0; --i) { |
724 |
ForkJoinTask<?> t; |
725 |
if ((t = ts.get(i)) == null) { |
726 |
ex = new NullPointerException(); |
727 |
break; |
728 |
} |
729 |
if (i == 0) { |
730 |
if ((s = t.doExec()) >= 0) |
731 |
s = t.awaitJoin(false, true); |
732 |
if ((s & ABNORMAL) != 0) |
733 |
ex = t.getException(); |
734 |
break; |
735 |
} |
736 |
t.fork(); |
737 |
} |
738 |
if (ex == null) { |
739 |
for (int i = 1, s; i <= last; ++i) { |
740 |
ForkJoinTask<?> t; |
741 |
if ((t = ts.get(i)) != null) { |
742 |
if ((s = t.status) >= 0) |
743 |
s = t.awaitJoin(false, false); |
744 |
if ((s & ABNORMAL) != 0) { |
745 |
ex = t.getException(); |
746 |
break; |
747 |
} |
748 |
} |
749 |
} |
750 |
} |
751 |
if (ex != null) { |
752 |
for (int i = 0, s; i <= last; ++i) { |
753 |
ForkJoinTask<?> t; |
754 |
if ((t = ts.get(i)) != null) |
755 |
t.cancel(false); |
756 |
} |
757 |
rethrow(ex); |
758 |
} |
759 |
return tasks; |
760 |
} |
761 |
|
762 |
/** |
763 |
* Attempts to cancel execution of this task. This attempt will |
764 |
* fail if the task has already completed or could not be |
765 |
* cancelled for some other reason. If successful, and this task |
766 |
* has not started when {@code cancel} is called, execution of |
767 |
* this task is suppressed. After this method returns |
768 |
* successfully, unless there is an intervening call to {@link |
769 |
* #reinitialize}, subsequent calls to {@link #isCancelled}, |
770 |
* {@link #isDone}, and {@code cancel} will return {@code true} |
771 |
* and calls to {@link #join} and related methods will result in |
772 |
* {@code CancellationException}. |
773 |
* |
774 |
* <p>This method may be overridden in subclasses, but if so, must |
775 |
* still ensure that these properties hold. In particular, the |
776 |
* {@code cancel} method itself must not throw exceptions. |
777 |
* |
778 |
* <p>This method is designed to be invoked by <em>other</em> |
779 |
* tasks. To terminate the current task, you can just return or |
780 |
* throw an unchecked exception from its computation method, or |
781 |
* invoke {@link #completeExceptionally(Throwable)}. |
782 |
* |
783 |
* @param mayInterruptIfRunning this value has no effect in the |
784 |
* default implementation because interrupts are not used to |
785 |
* control cancellation. |
786 |
* |
787 |
* @return {@code true} if this task is now cancelled |
788 |
*/ |
789 |
public boolean cancel(boolean mayInterruptIfRunning) { |
790 |
return (trySetCancelled() & (ABNORMAL | THROWN)) == ABNORMAL; |
791 |
} |
792 |
|
793 |
public final boolean isDone() { |
794 |
return status < 0; |
795 |
} |
796 |
|
797 |
public final boolean isCancelled() { |
798 |
return (status & (ABNORMAL | THROWN)) == ABNORMAL; |
799 |
} |
800 |
|
801 |
/** |
802 |
* Returns {@code true} if this task threw an exception or was cancelled. |
803 |
* |
804 |
* @return {@code true} if this task threw an exception or was cancelled |
805 |
*/ |
806 |
public final boolean isCompletedAbnormally() { |
807 |
return (status & ABNORMAL) != 0; |
808 |
} |
809 |
|
810 |
/** |
811 |
* Returns {@code true} if this task completed without throwing an |
812 |
* exception and was not cancelled. |
813 |
* |
814 |
* @return {@code true} if this task completed without throwing an |
815 |
* exception and was not cancelled |
816 |
*/ |
817 |
public final boolean isCompletedNormally() { |
818 |
return (status & (DONE | ABNORMAL)) == DONE; |
819 |
} |
820 |
|
821 |
/** |
822 |
* Returns the exception thrown by the base computation, or a |
823 |
* {@code CancellationException} if cancelled, or {@code null} if |
824 |
* none or if the method has not yet completed. |
825 |
* |
826 |
* @return the exception, or {@code null} if none |
827 |
*/ |
828 |
public final Throwable getException() { |
829 |
int s = status; |
830 |
return ((s & ABNORMAL) == 0 ? null : |
831 |
(s & THROWN) == 0 ? new CancellationException() : |
832 |
getThrowableException()); |
833 |
} |
834 |
|
835 |
/** |
836 |
* Completes this task abnormally, and if not already aborted or |
837 |
* cancelled, causes it to throw the given exception upon |
838 |
* {@code join} and related operations. This method may be used |
839 |
* to induce exceptions in asynchronous tasks, or to force |
840 |
* completion of tasks that would not otherwise complete. Its use |
841 |
* in other situations is discouraged. This method is |
842 |
* overridable, but overridden versions must invoke {@code super} |
843 |
* implementation to maintain guarantees. |
844 |
* |
845 |
* @param ex the exception to throw. If this exception is not a |
846 |
* {@code RuntimeException} or {@code Error}, the actual exception |
847 |
* thrown will be a {@code RuntimeException} with cause {@code ex}. |
848 |
*/ |
849 |
public void completeExceptionally(Throwable ex) { |
850 |
trySetException((ex instanceof RuntimeException) || |
851 |
(ex instanceof Error) ? ex : |
852 |
new RuntimeException(ex)); |
853 |
} |
854 |
|
855 |
/** |
856 |
* Completes this task, and if not already aborted or cancelled, |
857 |
* returning the given value as the result of subsequent |
858 |
* invocations of {@code join} and related operations. This method |
859 |
* may be used to provide results for asynchronous tasks, or to |
860 |
* provide alternative handling for tasks that would not otherwise |
861 |
* complete normally. Its use in other situations is |
862 |
* discouraged. This method is overridable, but overridden |
863 |
* versions must invoke {@code super} implementation to maintain |
864 |
* guarantees. |
865 |
* |
866 |
* @param value the result value for this task |
867 |
*/ |
868 |
public void complete(V value) { |
869 |
try { |
870 |
setRawResult(value); |
871 |
} catch (Throwable rex) { |
872 |
trySetException(rex); |
873 |
return; |
874 |
} |
875 |
setDone(); |
876 |
} |
877 |
|
878 |
/** |
879 |
* Completes this task normally without setting a value. The most |
880 |
* recent value established by {@link #setRawResult} (or {@code |
881 |
* null} by default) will be returned as the result of subsequent |
882 |
* invocations of {@code join} and related operations. |
883 |
* |
884 |
* @since 1.8 |
885 |
*/ |
886 |
public final void quietlyComplete() { |
887 |
setDone(); |
888 |
} |
889 |
|
890 |
/** |
891 |
* Waits if necessary for the computation to complete, and then |
892 |
* retrieves its result. |
893 |
* |
894 |
* @return the computed result |
895 |
* @throws CancellationException if the computation was cancelled |
896 |
* @throws ExecutionException if the computation threw an |
897 |
* exception |
898 |
* @throws InterruptedException if the current thread is not a |
899 |
* member of a ForkJoinPool and was interrupted while waiting |
900 |
*/ |
901 |
public final V get() throws InterruptedException, ExecutionException { |
902 |
int s; |
903 |
if (Thread.interrupted()) |
904 |
s = INTRPT; |
905 |
else if ((s = status) >= 0) |
906 |
s = awaitJoin(true, false); |
907 |
if (s == INTRPT) |
908 |
throw new InterruptedException(); |
909 |
else if ((s & THROWN) != 0) |
910 |
throw new ExecutionException(getThrowableException()); |
911 |
else if ((s & ABNORMAL) != 0) |
912 |
throw new CancellationException(); |
913 |
else |
914 |
return getRawResult(); |
915 |
} |
916 |
|
917 |
/** |
918 |
* Waits if necessary for at most the given time for the computation |
919 |
* to complete, and then retrieves its result, if available. |
920 |
* |
921 |
* @param timeout the maximum time to wait |
922 |
* @param unit the time unit of the timeout argument |
923 |
* @return the computed result |
924 |
* @throws CancellationException if the computation was cancelled |
925 |
* @throws ExecutionException if the computation threw an |
926 |
* exception |
927 |
* @throws InterruptedException if the current thread is not a |
928 |
* member of a ForkJoinPool and was interrupted while waiting |
929 |
* @throws TimeoutException if the wait timed out |
930 |
*/ |
931 |
public final V get(long timeout, TimeUnit unit) |
932 |
throws InterruptedException, ExecutionException, TimeoutException { |
933 |
long nanos = unit.toNanos(timeout); |
934 |
int s; |
935 |
if (Thread.interrupted()) |
936 |
s = INTRPT; |
937 |
else if ((s = status) >= 0 && nanos > 0L) { |
938 |
long d = nanos + System.nanoTime(); |
939 |
long deadline = (d == 0L) ? 1L : d; // avoid 0 |
940 |
Thread t = Thread.currentThread(); |
941 |
ForkJoinPool p = (t instanceof ForkJoinWorkerThread) ? |
942 |
((ForkJoinWorkerThread)t).pool : ForkJoinPool.common; |
943 |
if (p != null && p.preCompensate() == 0) |
944 |
p = null; |
945 |
s = awaitDone(true, deadline, p); |
946 |
} |
947 |
|
948 |
if (s == INTRPT) |
949 |
throw new InterruptedException(); |
950 |
else if (s >= 0) |
951 |
throw new TimeoutException(); |
952 |
else if ((s & THROWN) != 0) |
953 |
throw new ExecutionException(getThrowableException()); |
954 |
else if ((s & ABNORMAL) != 0) |
955 |
throw new CancellationException(); |
956 |
else |
957 |
return getRawResult(); |
958 |
} |
959 |
|
960 |
/** |
961 |
* Joins this task, without returning its result or throwing its |
962 |
* exception. This method may be useful when processing |
963 |
* collections of tasks when some have been cancelled or otherwise |
964 |
* known to have aborted. |
965 |
*/ |
966 |
public final void quietlyJoin() { |
967 |
if (status >= 0) |
968 |
awaitJoin(false, false); |
969 |
} |
970 |
|
971 |
/** |
972 |
* Commences performing this task and awaits its completion if |
973 |
* necessary, without returning its result or throwing its |
974 |
* exception. |
975 |
*/ |
976 |
public final void quietlyInvoke() { |
977 |
if (doExec() >= 0) |
978 |
awaitJoin(false, true); |
979 |
} |
980 |
|
981 |
/** |
982 |
* Possibly executes tasks until the pool hosting the current task |
983 |
* {@linkplain ForkJoinPool#isQuiescent is quiescent}. This |
984 |
* method may be of use in designs in which many tasks are forked, |
985 |
* but none are explicitly joined, instead executing them until |
986 |
* all are processed. |
987 |
*/ |
988 |
public static void helpQuiesce() { |
989 |
Thread t; ForkJoinWorkerThread w; ForkJoinPool p; |
990 |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread && |
991 |
(p = (w = (ForkJoinWorkerThread)t).pool) != null) |
992 |
p.helpQuiescePool(w.workQueue); |
993 |
else |
994 |
ForkJoinPool.quiesceCommonPool(); |
995 |
} |
996 |
|
997 |
/** |
998 |
* Resets the internal bookkeeping state of this task, allowing a |
999 |
* subsequent {@code fork}. This method allows repeated reuse of |
1000 |
* this task, but only if reuse occurs when this task has either |
1001 |
* never been forked, or has been forked, then completed and all |
1002 |
* outstanding joins of this task have also completed. Effects |
1003 |
* under any other usage conditions are not guaranteed. |
1004 |
* This method may be useful when executing |
1005 |
* pre-constructed trees of subtasks in loops. |
1006 |
* |
1007 |
* <p>Upon completion of this method, {@code isDone()} reports |
1008 |
* {@code false}, and {@code getException()} reports {@code |
1009 |
* null}. However, the value returned by {@code getRawResult} is |
1010 |
* unaffected. To clear this value, you can invoke {@code |
1011 |
* setRawResult(null)}. |
1012 |
*/ |
1013 |
public void reinitialize() { |
1014 |
aux = null; |
1015 |
status = 0; |
1016 |
} |
1017 |
|
1018 |
/** |
1019 |
* Returns the pool hosting the current thread, or {@code null} |
1020 |
* if the current thread is executing outside of any ForkJoinPool. |
1021 |
* |
1022 |
* <p>This method returns {@code null} if and only if {@link |
1023 |
* #inForkJoinPool} returns {@code false}. |
1024 |
* |
1025 |
* @return the pool, or {@code null} if none |
1026 |
*/ |
1027 |
public static ForkJoinPool getPool() { |
1028 |
Thread t; |
1029 |
return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1030 |
((ForkJoinWorkerThread) t).pool : null); |
1031 |
} |
1032 |
|
1033 |
/** |
1034 |
* Returns {@code true} if the current thread is a {@link |
1035 |
* ForkJoinWorkerThread} executing as a ForkJoinPool computation. |
1036 |
* |
1037 |
* @return {@code true} if the current thread is a {@link |
1038 |
* ForkJoinWorkerThread} executing as a ForkJoinPool computation, |
1039 |
* or {@code false} otherwise |
1040 |
*/ |
1041 |
public static boolean inForkJoinPool() { |
1042 |
return Thread.currentThread() instanceof ForkJoinWorkerThread; |
1043 |
} |
1044 |
|
1045 |
/** |
1046 |
* Tries to unschedule this task for execution. This method will |
1047 |
* typically (but is not guaranteed to) succeed if this task is |
1048 |
* the most recently forked task by the current thread, and has |
1049 |
* not commenced executing in another thread. This method may be |
1050 |
* useful when arranging alternative local processing of tasks |
1051 |
* that could have been, but were not, stolen. |
1052 |
* |
1053 |
* @return {@code true} if unforked |
1054 |
*/ |
1055 |
public boolean tryUnfork() { |
1056 |
Thread t; ForkJoinPool.WorkQueue q; |
1057 |
return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1058 |
(q = ((ForkJoinWorkerThread)t).workQueue) != null && |
1059 |
q.tryUnpush(this) : |
1060 |
(q = ForkJoinPool.commonQueue()) != null && |
1061 |
q.externalTryUnpush(this)); |
1062 |
} |
1063 |
|
1064 |
/** |
1065 |
* Returns an estimate of the number of tasks that have been |
1066 |
* forked by the current worker thread but not yet executed. This |
1067 |
* value may be useful for heuristic decisions about whether to |
1068 |
* fork other tasks. |
1069 |
* |
1070 |
* @return the number of tasks |
1071 |
*/ |
1072 |
public static int getQueuedTaskCount() { |
1073 |
Thread t; ForkJoinPool.WorkQueue q; |
1074 |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) |
1075 |
q = ((ForkJoinWorkerThread)t).workQueue; |
1076 |
else |
1077 |
q = ForkJoinPool.commonQueue(); |
1078 |
return (q == null) ? 0 : q.queueSize(); |
1079 |
} |
1080 |
|
1081 |
/** |
1082 |
* Returns an estimate of how many more locally queued tasks are |
1083 |
* held by the current worker thread than there are other worker |
1084 |
* threads that might steal them, or zero if this thread is not |
1085 |
* operating in a ForkJoinPool. This value may be useful for |
1086 |
* heuristic decisions about whether to fork other tasks. In many |
1087 |
* usages of ForkJoinTasks, at steady state, each worker should |
1088 |
* aim to maintain a small constant surplus (for example, 3) of |
1089 |
* tasks, and to process computations locally if this threshold is |
1090 |
* exceeded. |
1091 |
* |
1092 |
* @return the surplus number of tasks, which may be negative |
1093 |
*/ |
1094 |
public static int getSurplusQueuedTaskCount() { |
1095 |
return ForkJoinPool.getSurplusQueuedTaskCount(); |
1096 |
} |
1097 |
|
1098 |
// Extension methods |
1099 |
|
1100 |
/** |
1101 |
* Returns the result that would be returned by {@link #join}, even |
1102 |
* if this task completed abnormally, or {@code null} if this task |
1103 |
* is not known to have been completed. This method is designed |
1104 |
* to aid debugging, as well as to support extensions. Its use in |
1105 |
* any other context is discouraged. |
1106 |
* |
1107 |
* @return the result, or {@code null} if not completed |
1108 |
*/ |
1109 |
public abstract V getRawResult(); |
1110 |
|
1111 |
/** |
1112 |
* Forces the given value to be returned as a result. This method |
1113 |
* is designed to support extensions, and should not in general be |
1114 |
* called otherwise. |
1115 |
* |
1116 |
* @param value the value |
1117 |
*/ |
1118 |
protected abstract void setRawResult(V value); |
1119 |
|
1120 |
/** |
1121 |
* Immediately performs the base action of this task and returns |
1122 |
* true if, upon return from this method, this task is guaranteed |
1123 |
* to have completed. This method may return false otherwise, to |
1124 |
* indicate that this task is not necessarily complete (or is not |
1125 |
* known to be complete), for example in asynchronous actions that |
1126 |
* require explicit invocations of completion methods. This method |
1127 |
* may also throw an (unchecked) exception to indicate abnormal |
1128 |
* exit. This method is designed to support extensions, and should |
1129 |
* not in general be called otherwise. |
1130 |
* |
1131 |
* @return {@code true} if this task is known to have completed normally |
1132 |
*/ |
1133 |
protected abstract boolean exec(); |
1134 |
|
1135 |
/** |
1136 |
* Returns, but does not unschedule or execute, a task queued by |
1137 |
* the current thread but not yet executed, if one is immediately |
1138 |
* available. There is no guarantee that this task will actually |
1139 |
* be polled or executed next. Conversely, this method may return |
1140 |
* null even if a task exists but cannot be accessed without |
1141 |
* contention with other threads. This method is designed |
1142 |
* primarily to support extensions, and is unlikely to be useful |
1143 |
* otherwise. |
1144 |
* |
1145 |
* @return the next task, or {@code null} if none are available |
1146 |
*/ |
1147 |
protected static ForkJoinTask<?> peekNextLocalTask() { |
1148 |
Thread t; ForkJoinPool.WorkQueue q; |
1149 |
if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) |
1150 |
q = ((ForkJoinWorkerThread)t).workQueue; |
1151 |
else |
1152 |
q = ForkJoinPool.commonQueue(); |
1153 |
return (q == null) ? null : q.peek(); |
1154 |
} |
1155 |
|
1156 |
/** |
1157 |
* Unschedules and returns, without executing, the next task |
1158 |
* queued by the current thread but not yet executed, if the |
1159 |
* current thread is operating in a ForkJoinPool. This method is |
1160 |
* designed primarily to support extensions, and is unlikely to be |
1161 |
* useful otherwise. |
1162 |
* |
1163 |
* @return the next task, or {@code null} if none are available |
1164 |
*/ |
1165 |
protected static ForkJoinTask<?> pollNextLocalTask() { |
1166 |
Thread t; |
1167 |
return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1168 |
((ForkJoinWorkerThread)t).workQueue.nextLocalTask() : null); |
1169 |
} |
1170 |
|
1171 |
/** |
1172 |
* If the current thread is operating in a ForkJoinPool, |
1173 |
* unschedules and returns, without executing, the next task |
1174 |
* queued by the current thread but not yet executed, if one is |
1175 |
* available, or if not available, a task that was forked by some |
1176 |
* other thread, if available. Availability may be transient, so a |
1177 |
* {@code null} result does not necessarily imply quiescence of |
1178 |
* the pool this task is operating in. This method is designed |
1179 |
* primarily to support extensions, and is unlikely to be useful |
1180 |
* otherwise. |
1181 |
* |
1182 |
* @return a task, or {@code null} if none are available |
1183 |
*/ |
1184 |
protected static ForkJoinTask<?> pollTask() { |
1185 |
Thread t; ForkJoinWorkerThread w; |
1186 |
return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1187 |
(w = (ForkJoinWorkerThread)t).pool.nextTaskFor(w.workQueue) : |
1188 |
null); |
1189 |
} |
1190 |
|
1191 |
/** |
1192 |
* If the current thread is operating in a ForkJoinPool, |
1193 |
* unschedules and returns, without executing, a task externally |
1194 |
* submitted to the pool, if one is available. Availability may be |
1195 |
* transient, so a {@code null} result does not necessarily imply |
1196 |
* quiescence of the pool. This method is designed primarily to |
1197 |
* support extensions, and is unlikely to be useful otherwise. |
1198 |
* |
1199 |
* @return a task, or {@code null} if none are available |
1200 |
* @since 9 |
1201 |
*/ |
1202 |
protected static ForkJoinTask<?> pollSubmission() { |
1203 |
Thread t; |
1204 |
return (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) ? |
1205 |
((ForkJoinWorkerThread)t).pool.pollSubmission() : null); |
1206 |
} |
1207 |
|
1208 |
// tag operations |
1209 |
|
1210 |
/** |
1211 |
* Returns the tag for this task. |
1212 |
* |
1213 |
* @return the tag for this task |
1214 |
* @since 1.8 |
1215 |
*/ |
1216 |
public final short getForkJoinTaskTag() { |
1217 |
return (short)status; |
1218 |
} |
1219 |
|
1220 |
/** |
1221 |
* Atomically sets the tag value for this task and returns the old value. |
1222 |
* |
1223 |
* @param newValue the new tag value |
1224 |
* @return the previous value of the tag |
1225 |
* @since 1.8 |
1226 |
*/ |
1227 |
public final short setForkJoinTaskTag(short newValue) { |
1228 |
for (int s;;) { |
1229 |
if (casStatus(s = status, (s & ~SMASK) | (newValue & SMASK))) |
1230 |
return (short)s; |
1231 |
} |
1232 |
} |
1233 |
|
1234 |
/** |
1235 |
* Atomically conditionally sets the tag value for this task. |
1236 |
* Among other applications, tags can be used as visit markers |
1237 |
* in tasks operating on graphs, as in methods that check: {@code |
1238 |
* if (task.compareAndSetForkJoinTaskTag((short)0, (short)1))} |
1239 |
* before processing, otherwise exiting because the node has |
1240 |
* already been visited. |
1241 |
* |
1242 |
* @param expect the expected tag value |
1243 |
* @param update the new tag value |
1244 |
* @return {@code true} if successful; i.e., the current value was |
1245 |
* equal to {@code expect} and was changed to {@code update}. |
1246 |
* @since 1.8 |
1247 |
*/ |
1248 |
public final boolean compareAndSetForkJoinTaskTag(short expect, short update) { |
1249 |
for (int s;;) { |
1250 |
if ((short)(s = status) != expect) |
1251 |
return false; |
1252 |
if (casStatus(s, (s & ~SMASK) | (update & SMASK))) |
1253 |
return true; |
1254 |
} |
1255 |
} |
1256 |
|
1257 |
/** |
1258 |
* Adapter for Runnables. This implements RunnableFuture |
1259 |
* to be compliant with AbstractExecutorService constraints |
1260 |
* when used in ForkJoinPool. |
1261 |
*/ |
1262 |
static final class AdaptedRunnable<T> extends ForkJoinTask<T> |
1263 |
implements RunnableFuture<T> { |
1264 |
@SuppressWarnings("serial") // Conditionally serializable |
1265 |
final Runnable runnable; |
1266 |
@SuppressWarnings("serial") // Conditionally serializable |
1267 |
T result; |
1268 |
AdaptedRunnable(Runnable runnable, T result) { |
1269 |
if (runnable == null) throw new NullPointerException(); |
1270 |
this.runnable = runnable; |
1271 |
this.result = result; // OK to set this even before completion |
1272 |
} |
1273 |
public final T getRawResult() { return result; } |
1274 |
public final void setRawResult(T v) { result = v; } |
1275 |
public final boolean exec() { runnable.run(); return true; } |
1276 |
public final void run() { invoke(); } |
1277 |
public String toString() { |
1278 |
return super.toString() + "[Wrapped task = " + runnable + "]"; |
1279 |
} |
1280 |
private static final long serialVersionUID = 5232453952276885070L; |
1281 |
} |
1282 |
|
1283 |
/** |
1284 |
* Adapter for Runnables without results. |
1285 |
*/ |
1286 |
static final class AdaptedRunnableAction extends ForkJoinTask<Void> |
1287 |
implements RunnableFuture<Void> { |
1288 |
@SuppressWarnings("serial") // Conditionally serializable |
1289 |
final Runnable runnable; |
1290 |
AdaptedRunnableAction(Runnable runnable) { |
1291 |
if (runnable == null) throw new NullPointerException(); |
1292 |
this.runnable = runnable; |
1293 |
} |
1294 |
public final Void getRawResult() { return null; } |
1295 |
public final void setRawResult(Void v) { } |
1296 |
public final boolean exec() { runnable.run(); return true; } |
1297 |
public final void run() { invoke(); } |
1298 |
public String toString() { |
1299 |
return super.toString() + "[Wrapped task = " + runnable + "]"; |
1300 |
} |
1301 |
private static final long serialVersionUID = 5232453952276885070L; |
1302 |
} |
1303 |
|
1304 |
/** |
1305 |
* Adapter for Runnables in which failure forces worker exception. |
1306 |
*/ |
1307 |
static final class RunnableExecuteAction extends ForkJoinTask<Void> { |
1308 |
@SuppressWarnings("serial") // Conditionally serializable |
1309 |
final Runnable runnable; |
1310 |
RunnableExecuteAction(Runnable runnable) { |
1311 |
if (runnable == null) throw new NullPointerException(); |
1312 |
this.runnable = runnable; |
1313 |
} |
1314 |
public final Void getRawResult() { return null; } |
1315 |
public final void setRawResult(Void v) { } |
1316 |
public final boolean exec() { runnable.run(); return true; } |
1317 |
int trySetException(Throwable ex) { |
1318 |
int s; |
1319 |
if (isExceptionalStatus(s = trySetThrown(ex))) |
1320 |
rethrow(ex); // rethrow outside exec() catches. |
1321 |
return s; |
1322 |
} |
1323 |
private static final long serialVersionUID = 5232453952276885070L; |
1324 |
} |
1325 |
|
1326 |
/** |
1327 |
* Adapter for Callables. |
1328 |
*/ |
1329 |
static final class AdaptedCallable<T> extends ForkJoinTask<T> |
1330 |
implements RunnableFuture<T> { |
1331 |
@SuppressWarnings("serial") // Conditionally serializable |
1332 |
final Callable<? extends T> callable; |
1333 |
@SuppressWarnings("serial") // Conditionally serializable |
1334 |
T result; |
1335 |
AdaptedCallable(Callable<? extends T> callable) { |
1336 |
if (callable == null) throw new NullPointerException(); |
1337 |
this.callable = callable; |
1338 |
} |
1339 |
public final T getRawResult() { return result; } |
1340 |
public final void setRawResult(T v) { result = v; } |
1341 |
public final boolean exec() { |
1342 |
try { |
1343 |
result = callable.call(); |
1344 |
return true; |
1345 |
} catch (RuntimeException rex) { |
1346 |
throw rex; |
1347 |
} catch (Exception ex) { |
1348 |
throw new RuntimeException(ex); |
1349 |
} |
1350 |
} |
1351 |
public final void run() { invoke(); } |
1352 |
public String toString() { |
1353 |
return super.toString() + "[Wrapped task = " + callable + "]"; |
1354 |
} |
1355 |
private static final long serialVersionUID = 2838392045355241008L; |
1356 |
} |
1357 |
|
1358 |
/** |
1359 |
* Returns a new {@code ForkJoinTask} that performs the {@code run} |
1360 |
* method of the given {@code Runnable} as its action, and returns |
1361 |
* a null result upon {@link #join}. |
1362 |
* |
1363 |
* @param runnable the runnable action |
1364 |
* @return the task |
1365 |
*/ |
1366 |
public static ForkJoinTask<?> adapt(Runnable runnable) { |
1367 |
return new AdaptedRunnableAction(runnable); |
1368 |
} |
1369 |
|
1370 |
/** |
1371 |
* Returns a new {@code ForkJoinTask} that performs the {@code run} |
1372 |
* method of the given {@code Runnable} as its action, and returns |
1373 |
* the given result upon {@link #join}. |
1374 |
* |
1375 |
* @param runnable the runnable action |
1376 |
* @param result the result upon completion |
1377 |
* @param <T> the type of the result |
1378 |
* @return the task |
1379 |
*/ |
1380 |
public static <T> ForkJoinTask<T> adapt(Runnable runnable, T result) { |
1381 |
return new AdaptedRunnable<T>(runnable, result); |
1382 |
} |
1383 |
|
1384 |
/** |
1385 |
* Returns a new {@code ForkJoinTask} that performs the {@code call} |
1386 |
* method of the given {@code Callable} as its action, and returns |
1387 |
* its result upon {@link #join}, translating any checked exceptions |
1388 |
* encountered into {@code RuntimeException}. |
1389 |
* |
1390 |
* @param callable the callable action |
1391 |
* @param <T> the type of the callable's result |
1392 |
* @return the task |
1393 |
*/ |
1394 |
public static <T> ForkJoinTask<T> adapt(Callable<? extends T> callable) { |
1395 |
return new AdaptedCallable<T>(callable); |
1396 |
} |
1397 |
|
1398 |
// Serialization support |
1399 |
|
1400 |
private static final long serialVersionUID = -7721805057305804111L; |
1401 |
|
1402 |
/** |
1403 |
* Saves this task to a stream (that is, serializes it). |
1404 |
* |
1405 |
* @param s the stream |
1406 |
* @throws java.io.IOException if an I/O error occurs |
1407 |
* @serialData the current run status and the exception thrown |
1408 |
* during execution, or {@code null} if none |
1409 |
*/ |
1410 |
private void writeObject(java.io.ObjectOutputStream s) |
1411 |
throws java.io.IOException { |
1412 |
Aux a; |
1413 |
s.defaultWriteObject(); |
1414 |
s.writeObject((a = aux) == null ? null : a.ex); |
1415 |
} |
1416 |
|
1417 |
/** |
1418 |
* Reconstitutes this task from a stream (that is, deserializes it). |
1419 |
* @param s the stream |
1420 |
* @throws ClassNotFoundException if the class of a serialized object |
1421 |
* could not be found |
1422 |
* @throws java.io.IOException if an I/O error occurs |
1423 |
*/ |
1424 |
private void readObject(java.io.ObjectInputStream s) |
1425 |
throws java.io.IOException, ClassNotFoundException { |
1426 |
s.defaultReadObject(); |
1427 |
Object ex = s.readObject(); |
1428 |
if (ex != null) |
1429 |
trySetThrown((Throwable)ex); |
1430 |
} |
1431 |
|
1432 |
static { |
1433 |
try { |
1434 |
MethodHandles.Lookup l = MethodHandles.lookup(); |
1435 |
STATUS = l.findVarHandle(ForkJoinTask.class, "status", int.class); |
1436 |
AUX = l.findVarHandle(ForkJoinTask.class, "aux", Aux.class); |
1437 |
} catch (ReflectiveOperationException e) { |
1438 |
throw new ExceptionInInitializerError(e); |
1439 |
} |
1440 |
} |
1441 |
|
1442 |
} |