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