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