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