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/licenses/publicdomain |
5 |
*/ |
6 |
|
7 |
package java.util.concurrent; |
8 |
|
9 |
import java.io.Serializable; |
10 |
import java.util.Collection; |
11 |
import java.util.Collections; |
12 |
import java.util.List; |
13 |
import java.util.Map; |
14 |
import java.util.WeakHashMap; |
15 |
|
16 |
/** |
17 |
* Abstract base class for tasks that run within a {@link |
18 |
* ForkJoinPool}. A ForkJoinTask is a thread-like entity that is much |
19 |
* lighter weight than a normal thread. Huge numbers of tasks and |
20 |
* subtasks may be hosted by a small number of actual threads in a |
21 |
* ForkJoinPool, at the price of some usage limitations. |
22 |
* |
23 |
* <p> A "main" ForkJoinTask begins execution when submitted to a |
24 |
* {@link ForkJoinPool}. Once started, it will usually in turn start |
25 |
* other subtasks. As indicated by the name of this class, many |
26 |
* programs using ForkJoinTasks employ only methods {@code fork} |
27 |
* and {@code join}, or derivatives such as |
28 |
* {@code invokeAll}. However, this class also provides a number |
29 |
* of other methods that can come into play in advanced usages, as |
30 |
* well as extension mechanics that allow support of new forms of |
31 |
* fork/join processing. |
32 |
* |
33 |
* <p>A ForkJoinTask is a lightweight form of {@link Future}. The |
34 |
* efficiency of ForkJoinTasks stems from a set of restrictions (that |
35 |
* are only partially statically enforceable) reflecting their |
36 |
* intended use as computational tasks calculating pure functions or |
37 |
* operating on purely isolated objects. The primary coordination |
38 |
* mechanisms are {@link #fork}, that arranges asynchronous execution, |
39 |
* and {@link #join}, that doesn't proceed until the task's result has |
40 |
* been computed. Computations should avoid {@code synchronized} |
41 |
* methods or blocks, and should minimize other blocking |
42 |
* synchronization apart from joining other tasks or using |
43 |
* synchronizers such as Phasers that are advertised to cooperate with |
44 |
* fork/join scheduling. Tasks should also not perform blocking IO, |
45 |
* and should ideally access variables that are completely independent |
46 |
* of those accessed by other running tasks. Minor breaches of these |
47 |
* restrictions, for example using shared output streams, may be |
48 |
* tolerable in practice, but frequent use may result in poor |
49 |
* performance, and the potential to indefinitely stall if the number |
50 |
* of threads not waiting for IO or other external synchronization |
51 |
* becomes exhausted. This usage restriction is in part enforced by |
52 |
* not permitting checked exceptions such as {@code IOExceptions} |
53 |
* to be thrown. However, computations may still encounter unchecked |
54 |
* exceptions, that are rethrown to callers attempting join |
55 |
* them. These exceptions may additionally include |
56 |
* RejectedExecutionExceptions stemming from internal resource |
57 |
* exhaustion such as failure to allocate internal task queues. |
58 |
* |
59 |
* <p>The primary method for awaiting completion and extracting |
60 |
* results of a task is {@link #join}, but there are several variants: |
61 |
* The {@link Future#get} methods support interruptible and/or timed |
62 |
* waits for completion and report results using {@code Future} |
63 |
* conventions. Method {@link #helpJoin} enables callers to actively |
64 |
* execute other tasks while awaiting joins, which is sometimes more |
65 |
* efficient but only applies when all subtasks are known to be |
66 |
* strictly tree-structured. Method {@link #invoke} is semantically |
67 |
* equivalent to {@code fork(); join()} but always attempts to |
68 |
* begin execution in the current thread. The "<em>quiet</em>" forms |
69 |
* of these methods do not extract results or report exceptions. These |
70 |
* may be useful when a set of tasks are being executed, and you need |
71 |
* to delay processing of results or exceptions until all complete. |
72 |
* Method {@code invokeAll} (available in multiple versions) |
73 |
* performs the most common form of parallel invocation: forking a set |
74 |
* of tasks and joining them all. |
75 |
* |
76 |
* <p> The ForkJoinTask class is not usually directly subclassed. |
77 |
* Instead, you subclass one of the abstract classes that support a |
78 |
* particular style of fork/join processing. Normally, a concrete |
79 |
* ForkJoinTask subclass declares fields comprising its parameters, |
80 |
* established in a constructor, and then defines a {@code compute} |
81 |
* method that somehow uses the control methods supplied by this base |
82 |
* class. While these methods have {@code public} access (to allow |
83 |
* instances of different task subclasses to call each others |
84 |
* methods), some of them may only be called from within other |
85 |
* ForkJoinTasks (as may be determined using method {@link |
86 |
* #inForkJoinPool}). Attempts to invoke them in other contexts |
87 |
* result in exceptions or errors, possibly including |
88 |
* ClassCastException. |
89 |
* |
90 |
* <p>Most base support methods are {@code final} because their |
91 |
* implementations are intrinsically tied to the underlying |
92 |
* lightweight task scheduling framework, and so cannot be overridden. |
93 |
* Developers creating new basic styles of fork/join processing should |
94 |
* minimally implement {@code protected} methods |
95 |
* {@code exec}, {@code setRawResult}, and |
96 |
* {@code getRawResult}, while also introducing an abstract |
97 |
* computational method that can be implemented in its subclasses, |
98 |
* possibly relying on other {@code protected} methods provided |
99 |
* by this class. |
100 |
* |
101 |
* <p>ForkJoinTasks should perform relatively small amounts of |
102 |
* computations, otherwise splitting into smaller tasks. As a very |
103 |
* rough rule of thumb, a task should perform more than 100 and less |
104 |
* than 10000 basic computational steps. If tasks are too big, then |
105 |
* parallelism cannot improve throughput. If too small, then memory |
106 |
* and internal task maintenance overhead may overwhelm processing. |
107 |
* |
108 |
* <p>ForkJoinTasks are {@code Serializable}, which enables them |
109 |
* to be used in extensions such as remote execution frameworks. It is |
110 |
* in general sensible to serialize tasks only before or after, but |
111 |
* not during execution. Serialization is not relied on during |
112 |
* execution itself. |
113 |
* |
114 |
* @since 1.7 |
115 |
* @author Doug Lea |
116 |
*/ |
117 |
public abstract class ForkJoinTask<V> implements Future<V>, Serializable { |
118 |
|
119 |
/** |
120 |
* Run control status bits packed into a single int to minimize |
121 |
* footprint and to ensure atomicity (via CAS). Status is |
122 |
* initially zero, and takes on nonnegative values until |
123 |
* completed, upon which status holds COMPLETED. CANCELLED, or |
124 |
* EXCEPTIONAL, which use the top 3 bits. Tasks undergoing |
125 |
* blocking waits by other threads have SIGNAL_MASK bits set -- |
126 |
* bit 15 for external (nonFJ) waits, and the rest a count of |
127 |
* waiting FJ threads. (This representation relies on |
128 |
* ForkJoinPool max thread limits). Completion of a stolen task |
129 |
* with SIGNAL_MASK bits set awakens waiter via notifyAll. Even |
130 |
* though suboptimal for some purposes, we use basic builtin |
131 |
* wait/notify to take advantage of "monitor inflation" in JVMs |
132 |
* that we would otherwise need to emulate to avoid adding further |
133 |
* per-task bookkeeping overhead. Note that bits 16-28 are |
134 |
* currently unused. Also value 0x80000000 is available as spare |
135 |
* completion value. |
136 |
*/ |
137 |
volatile int status; // accessed directly by pool and workers |
138 |
|
139 |
static final int COMPLETION_MASK = 0xe0000000; |
140 |
static final int NORMAL = 0xe0000000; // == mask |
141 |
static final int CANCELLED = 0xc0000000; |
142 |
static final int EXCEPTIONAL = 0xa0000000; |
143 |
static final int SIGNAL_MASK = 0x0000ffff; |
144 |
static final int INTERNAL_SIGNAL_MASK = 0x00007fff; |
145 |
static final int EXTERNAL_SIGNAL = 0x00008000; // top bit of low word |
146 |
|
147 |
/** |
148 |
* Table of exceptions thrown by tasks, to enable reporting by |
149 |
* callers. Because exceptions are rare, we don't directly keep |
150 |
* them with task objects, but instead use a weak ref table. Note |
151 |
* that cancellation exceptions don't appear in the table, but are |
152 |
* instead recorded as status values. |
153 |
* TODO: Use ConcurrentReferenceHashMap |
154 |
*/ |
155 |
static final Map<ForkJoinTask<?>, Throwable> exceptionMap = |
156 |
Collections.synchronizedMap |
157 |
(new WeakHashMap<ForkJoinTask<?>, Throwable>()); |
158 |
|
159 |
// within-package utilities |
160 |
|
161 |
/** |
162 |
* Gets current worker thread, or null if not a worker thread. |
163 |
*/ |
164 |
static ForkJoinWorkerThread getWorker() { |
165 |
Thread t = Thread.currentThread(); |
166 |
return ((t instanceof ForkJoinWorkerThread) ? |
167 |
(ForkJoinWorkerThread) t : null); |
168 |
} |
169 |
|
170 |
final boolean casStatus(int cmp, int val) { |
171 |
return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val); |
172 |
} |
173 |
|
174 |
/** |
175 |
* Workaround for not being able to rethrow unchecked exceptions. |
176 |
*/ |
177 |
static void rethrowException(Throwable ex) { |
178 |
if (ex != null) |
179 |
UNSAFE.throwException(ex); |
180 |
} |
181 |
|
182 |
// Setting completion status |
183 |
|
184 |
/** |
185 |
* Marks completion and wakes up threads waiting to join this task. |
186 |
* |
187 |
* @param completion one of NORMAL, CANCELLED, EXCEPTIONAL |
188 |
*/ |
189 |
final void setCompletion(int completion) { |
190 |
ForkJoinPool pool = getPool(); |
191 |
if (pool != null) { |
192 |
int s; // Clear signal bits while setting completion status |
193 |
do {} while ((s = status) >= 0 && !casStatus(s, completion)); |
194 |
|
195 |
if ((s & SIGNAL_MASK) != 0) { |
196 |
if ((s &= INTERNAL_SIGNAL_MASK) != 0) |
197 |
pool.updateRunningCount(s); |
198 |
synchronized (this) { notifyAll(); } |
199 |
} |
200 |
} |
201 |
else |
202 |
externallySetCompletion(completion); |
203 |
} |
204 |
|
205 |
/** |
206 |
* Version of setCompletion for non-FJ threads. Leaves signal |
207 |
* bits for unblocked threads to adjust, and always notifies. |
208 |
*/ |
209 |
private void externallySetCompletion(int completion) { |
210 |
int s; |
211 |
do {} while ((s = status) >= 0 && |
212 |
!casStatus(s, (s & SIGNAL_MASK) | completion)); |
213 |
synchronized (this) { notifyAll(); } |
214 |
} |
215 |
|
216 |
/** |
217 |
* Sets status to indicate normal completion. |
218 |
*/ |
219 |
final void setNormalCompletion() { |
220 |
// Try typical fast case -- single CAS, no signal, not already done. |
221 |
// Manually expand casStatus to improve chances of inlining it |
222 |
if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL)) |
223 |
setCompletion(NORMAL); |
224 |
} |
225 |
|
226 |
// internal waiting and notification |
227 |
|
228 |
/** |
229 |
* Performs the actual monitor wait for awaitDone. |
230 |
*/ |
231 |
private void doAwaitDone() { |
232 |
// Minimize lock bias and in/de-flation effects by maximizing |
233 |
// chances of waiting inside sync |
234 |
try { |
235 |
while (status >= 0) |
236 |
synchronized (this) { if (status >= 0) wait(); } |
237 |
} catch (InterruptedException ie) { |
238 |
onInterruptedWait(); |
239 |
} |
240 |
} |
241 |
|
242 |
/** |
243 |
* Performs the actual timed monitor wait for awaitDone. |
244 |
*/ |
245 |
private void doAwaitDone(long startTime, long nanos) { |
246 |
synchronized (this) { |
247 |
try { |
248 |
while (status >= 0) { |
249 |
long nt = nanos - System.nanoTime() - startTime; |
250 |
if (nt <= 0) |
251 |
break; |
252 |
wait(nt / 1000000, (int) (nt % 1000000)); |
253 |
} |
254 |
} catch (InterruptedException ie) { |
255 |
onInterruptedWait(); |
256 |
} |
257 |
} |
258 |
} |
259 |
|
260 |
// Awaiting completion |
261 |
|
262 |
/** |
263 |
* Sets status to indicate there is joiner, then waits for join, |
264 |
* surrounded with pool notifications. |
265 |
* |
266 |
* @return status upon exit |
267 |
*/ |
268 |
private int awaitDone(ForkJoinWorkerThread w, |
269 |
boolean maintainParallelism) { |
270 |
ForkJoinPool pool = (w == null) ? null : w.pool; |
271 |
int s; |
272 |
while ((s = status) >= 0) { |
273 |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
274 |
if (pool == null || !pool.preJoin(this, maintainParallelism)) |
275 |
doAwaitDone(); |
276 |
if (((s = status) & INTERNAL_SIGNAL_MASK) != 0) |
277 |
adjustPoolCountsOnUnblock(pool); |
278 |
break; |
279 |
} |
280 |
} |
281 |
return s; |
282 |
} |
283 |
|
284 |
/** |
285 |
* Timed version of awaitDone |
286 |
* |
287 |
* @return status upon exit |
288 |
*/ |
289 |
private int awaitDone(ForkJoinWorkerThread w, long nanos) { |
290 |
ForkJoinPool pool = (w == null) ? null : w.pool; |
291 |
int s; |
292 |
while ((s = status) >= 0) { |
293 |
if (casStatus(s, (pool == null) ? s|EXTERNAL_SIGNAL : s+1)) { |
294 |
long startTime = System.nanoTime(); |
295 |
if (pool == null || !pool.preJoin(this, false)) |
296 |
doAwaitDone(startTime, nanos); |
297 |
if ((s = status) >= 0) { |
298 |
adjustPoolCountsOnCancelledWait(pool); |
299 |
s = status; |
300 |
} |
301 |
if (s < 0 && (s & INTERNAL_SIGNAL_MASK) != 0) |
302 |
adjustPoolCountsOnUnblock(pool); |
303 |
break; |
304 |
} |
305 |
} |
306 |
return s; |
307 |
} |
308 |
|
309 |
/** |
310 |
* Notifies pool that thread is unblocked. Called by signalled |
311 |
* threads when woken by non-FJ threads (which is atypical). |
312 |
*/ |
313 |
private void adjustPoolCountsOnUnblock(ForkJoinPool pool) { |
314 |
int s; |
315 |
do {} while ((s = status) < 0 && !casStatus(s, s & COMPLETION_MASK)); |
316 |
if (pool != null && (s &= INTERNAL_SIGNAL_MASK) != 0) |
317 |
pool.updateRunningCount(s); |
318 |
} |
319 |
|
320 |
/** |
321 |
* Notifies pool to adjust counts on cancelled or timed out wait. |
322 |
*/ |
323 |
private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) { |
324 |
if (pool != null) { |
325 |
int s; |
326 |
while ((s = status) >= 0 && (s & INTERNAL_SIGNAL_MASK) != 0) { |
327 |
if (casStatus(s, s - 1)) { |
328 |
pool.updateRunningCount(1); |
329 |
break; |
330 |
} |
331 |
} |
332 |
} |
333 |
} |
334 |
|
335 |
/** |
336 |
* Handles interruptions during waits. |
337 |
*/ |
338 |
private void onInterruptedWait() { |
339 |
ForkJoinWorkerThread w = getWorker(); |
340 |
if (w == null) |
341 |
Thread.currentThread().interrupt(); // re-interrupt |
342 |
else if (w.isTerminating()) |
343 |
cancelIgnoringExceptions(); |
344 |
// else if FJworker, ignore interrupt |
345 |
} |
346 |
|
347 |
// Recording and reporting exceptions |
348 |
|
349 |
private void setDoneExceptionally(Throwable rex) { |
350 |
exceptionMap.put(this, rex); |
351 |
setCompletion(EXCEPTIONAL); |
352 |
} |
353 |
|
354 |
/** |
355 |
* Throws the exception associated with status s. |
356 |
* |
357 |
* @throws the exception |
358 |
*/ |
359 |
private void reportException(int s) { |
360 |
if ((s &= COMPLETION_MASK) < NORMAL) { |
361 |
if (s == CANCELLED) |
362 |
throw new CancellationException(); |
363 |
else |
364 |
rethrowException(exceptionMap.get(this)); |
365 |
} |
366 |
} |
367 |
|
368 |
/** |
369 |
* Returns result or throws exception using j.u.c.Future conventions. |
370 |
* Only call when {@code isDone} known to be true. |
371 |
*/ |
372 |
private V reportFutureResult() |
373 |
throws ExecutionException, InterruptedException { |
374 |
int s = status & COMPLETION_MASK; |
375 |
if (s < NORMAL) { |
376 |
Throwable ex; |
377 |
if (s == CANCELLED) |
378 |
throw new CancellationException(); |
379 |
if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null) |
380 |
throw new ExecutionException(ex); |
381 |
if (Thread.interrupted()) |
382 |
throw new InterruptedException(); |
383 |
} |
384 |
return getRawResult(); |
385 |
} |
386 |
|
387 |
/** |
388 |
* Returns result or throws exception using j.u.c.Future conventions |
389 |
* with timeouts. |
390 |
*/ |
391 |
private V reportTimedFutureResult() |
392 |
throws InterruptedException, ExecutionException, TimeoutException { |
393 |
Throwable ex; |
394 |
int s = status & COMPLETION_MASK; |
395 |
if (s == NORMAL) |
396 |
return getRawResult(); |
397 |
if (s == CANCELLED) |
398 |
throw new CancellationException(); |
399 |
if (s == EXCEPTIONAL && (ex = exceptionMap.get(this)) != null) |
400 |
throw new ExecutionException(ex); |
401 |
if (Thread.interrupted()) |
402 |
throw new InterruptedException(); |
403 |
throw new TimeoutException(); |
404 |
} |
405 |
|
406 |
// internal execution methods |
407 |
|
408 |
/** |
409 |
* Calls exec, recording completion, and rethrowing exception if |
410 |
* encountered. Caller should normally check status before calling. |
411 |
* |
412 |
* @return true if completed normally |
413 |
*/ |
414 |
private boolean tryExec() { |
415 |
try { // try block must contain only call to exec |
416 |
if (!exec()) |
417 |
return false; |
418 |
} catch (Throwable rex) { |
419 |
setDoneExceptionally(rex); |
420 |
rethrowException(rex); |
421 |
return false; // not reached |
422 |
} |
423 |
setNormalCompletion(); |
424 |
return true; |
425 |
} |
426 |
|
427 |
/** |
428 |
* Main execution method used by worker threads. Invokes |
429 |
* base computation unless already complete. |
430 |
*/ |
431 |
final void quietlyExec() { |
432 |
if (status >= 0) { |
433 |
try { |
434 |
if (!exec()) |
435 |
return; |
436 |
} catch (Throwable rex) { |
437 |
setDoneExceptionally(rex); |
438 |
return; |
439 |
} |
440 |
setNormalCompletion(); |
441 |
} |
442 |
} |
443 |
|
444 |
/** |
445 |
* Calls exec(), recording but not rethrowing exception. |
446 |
* Caller should normally check status before calling. |
447 |
* |
448 |
* @return true if completed normally |
449 |
*/ |
450 |
private boolean tryQuietlyInvoke() { |
451 |
try { |
452 |
if (!exec()) |
453 |
return false; |
454 |
} catch (Throwable rex) { |
455 |
setDoneExceptionally(rex); |
456 |
return false; |
457 |
} |
458 |
setNormalCompletion(); |
459 |
return true; |
460 |
} |
461 |
|
462 |
/** |
463 |
* Cancels, ignoring any exceptions it throws. |
464 |
*/ |
465 |
final void cancelIgnoringExceptions() { |
466 |
try { |
467 |
cancel(false); |
468 |
} catch (Throwable ignore) { |
469 |
} |
470 |
} |
471 |
|
472 |
/** |
473 |
* Main implementation of helpJoin |
474 |
*/ |
475 |
private int busyJoin(ForkJoinWorkerThread w) { |
476 |
int s; |
477 |
ForkJoinTask<?> t; |
478 |
while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null) |
479 |
t.quietlyExec(); |
480 |
return (s >= 0) ? awaitDone(w, false) : s; // block if no work |
481 |
} |
482 |
|
483 |
// public methods |
484 |
|
485 |
/** |
486 |
* Arranges to asynchronously execute this task. While it is not |
487 |
* necessarily enforced, it is a usage error to fork a task more |
488 |
* than once unless it has completed and been reinitialized. This |
489 |
* method may be invoked only from within ForkJoinTask |
490 |
* computations (as may be determined using method {@link |
491 |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
492 |
* in exceptions or errors, possibly including ClassCastException. |
493 |
*/ |
494 |
public final void fork() { |
495 |
((ForkJoinWorkerThread) Thread.currentThread()) |
496 |
.pushTask(this); |
497 |
} |
498 |
|
499 |
/** |
500 |
* Returns the result of the computation when it is ready. |
501 |
* This method differs from {@code get} in that abnormal |
502 |
* completion results in RuntimeExceptions or Errors, not |
503 |
* ExecutionExceptions. |
504 |
* |
505 |
* @return the computed result |
506 |
*/ |
507 |
public final V join() { |
508 |
ForkJoinWorkerThread w = getWorker(); |
509 |
if (w == null || status < 0 || !w.unpushTask(this) || !tryExec()) |
510 |
reportException(awaitDone(w, true)); |
511 |
return getRawResult(); |
512 |
} |
513 |
|
514 |
/** |
515 |
* Commences performing this task, awaits its completion if |
516 |
* necessary, and return its result. |
517 |
* |
518 |
* @throws Throwable (a RuntimeException, Error, or unchecked |
519 |
* exception) if the underlying computation did so |
520 |
* @return the computed result |
521 |
*/ |
522 |
public final V invoke() { |
523 |
if (status >= 0 && tryExec()) |
524 |
return getRawResult(); |
525 |
else |
526 |
return join(); |
527 |
} |
528 |
|
529 |
/** |
530 |
* Forks both tasks, returning when {@code isDone} holds for |
531 |
* both of them or an exception is encountered. This method may be |
532 |
* invoked only from within ForkJoinTask computations (as may be |
533 |
* determined using method {@link #inForkJoinPool}). Attempts to |
534 |
* invoke in other contexts result in exceptions or errors, |
535 |
* possibly including ClassCastException. |
536 |
* |
537 |
* @param t1 one task |
538 |
* @param t2 the other task |
539 |
* @throws NullPointerException if t1 or t2 are null |
540 |
* @throws RuntimeException or Error if either task did so |
541 |
*/ |
542 |
public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) { |
543 |
t2.fork(); |
544 |
t1.invoke(); |
545 |
t2.join(); |
546 |
} |
547 |
|
548 |
/** |
549 |
* Forks the given tasks, returning when {@code isDone} holds |
550 |
* for all of them. If any task encounters an exception, others |
551 |
* may be cancelled. This method may be invoked only from within |
552 |
* ForkJoinTask computations (as may be determined using method |
553 |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
554 |
* result in exceptions or errors, possibly including |
555 |
* ClassCastException. |
556 |
* |
557 |
* @param tasks the array of tasks |
558 |
* @throws NullPointerException if tasks or any element are null |
559 |
* @throws RuntimeException or Error if any task did so |
560 |
*/ |
561 |
public static void invokeAll(ForkJoinTask<?>... tasks) { |
562 |
Throwable ex = null; |
563 |
int last = tasks.length - 1; |
564 |
for (int i = last; i >= 0; --i) { |
565 |
ForkJoinTask<?> t = tasks[i]; |
566 |
if (t == null) { |
567 |
if (ex == null) |
568 |
ex = new NullPointerException(); |
569 |
} |
570 |
else if (i != 0) |
571 |
t.fork(); |
572 |
else { |
573 |
t.quietlyInvoke(); |
574 |
if (ex == null) |
575 |
ex = t.getException(); |
576 |
} |
577 |
} |
578 |
for (int i = 1; i <= last; ++i) { |
579 |
ForkJoinTask<?> t = tasks[i]; |
580 |
if (t != null) { |
581 |
if (ex != null) |
582 |
t.cancel(false); |
583 |
else { |
584 |
t.quietlyJoin(); |
585 |
if (ex == null) |
586 |
ex = t.getException(); |
587 |
} |
588 |
} |
589 |
} |
590 |
if (ex != null) |
591 |
rethrowException(ex); |
592 |
} |
593 |
|
594 |
/** |
595 |
* Forks all tasks in the collection, returning when |
596 |
* {@code isDone} holds for all of them. If any task |
597 |
* encounters an exception, others may be cancelled. This method |
598 |
* may be invoked only from within ForkJoinTask computations (as |
599 |
* may be determined using method {@link |
600 |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
601 |
* in exceptions or errors, possibly including ClassCastException. |
602 |
* |
603 |
* @param tasks the collection of tasks |
604 |
* @throws NullPointerException if tasks or any element are null |
605 |
* @throws RuntimeException or Error if any task did so |
606 |
*/ |
607 |
public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) { |
608 |
if (!(tasks instanceof List<?>)) { |
609 |
invokeAll(tasks.toArray(new ForkJoinTask<?>[tasks.size()])); |
610 |
return; |
611 |
} |
612 |
@SuppressWarnings("unchecked") |
613 |
List<? extends ForkJoinTask<?>> ts = |
614 |
(List<? extends ForkJoinTask<?>>) tasks; |
615 |
Throwable ex = null; |
616 |
int last = ts.size() - 1; |
617 |
for (int i = last; i >= 0; --i) { |
618 |
ForkJoinTask<?> t = ts.get(i); |
619 |
if (t == null) { |
620 |
if (ex == null) |
621 |
ex = new NullPointerException(); |
622 |
} |
623 |
else if (i != 0) |
624 |
t.fork(); |
625 |
else { |
626 |
t.quietlyInvoke(); |
627 |
if (ex == null) |
628 |
ex = t.getException(); |
629 |
} |
630 |
} |
631 |
for (int i = 1; i <= last; ++i) { |
632 |
ForkJoinTask<?> t = ts.get(i); |
633 |
if (t != null) { |
634 |
if (ex != null) |
635 |
t.cancel(false); |
636 |
else { |
637 |
t.quietlyJoin(); |
638 |
if (ex == null) |
639 |
ex = t.getException(); |
640 |
} |
641 |
} |
642 |
} |
643 |
if (ex != null) |
644 |
rethrowException(ex); |
645 |
} |
646 |
|
647 |
/** |
648 |
* Returns true if the computation performed by this task has |
649 |
* completed (or has been cancelled). |
650 |
* |
651 |
* @return true if this computation has completed |
652 |
*/ |
653 |
public final boolean isDone() { |
654 |
return status < 0; |
655 |
} |
656 |
|
657 |
/** |
658 |
* Returns true if this task was cancelled. |
659 |
* |
660 |
* @return true if this task was cancelled |
661 |
*/ |
662 |
public final boolean isCancelled() { |
663 |
return (status & COMPLETION_MASK) == CANCELLED; |
664 |
} |
665 |
|
666 |
/** |
667 |
* Asserts that the results of this task's computation will not be |
668 |
* used. If a cancellation occurs before attempting to execute this |
669 |
* task, then execution will be suppressed, {@code isCancelled} |
670 |
* will report true, and {@code join} will result in a |
671 |
* {@code CancellationException} being thrown. Otherwise, when |
672 |
* cancellation races with completion, there are no guarantees |
673 |
* about whether {@code isCancelled} will report true, whether |
674 |
* {@code join} will return normally or via an exception, or |
675 |
* whether these behaviors will remain consistent upon repeated |
676 |
* invocation. |
677 |
* |
678 |
* <p>This method may be overridden in subclasses, but if so, must |
679 |
* still ensure that these minimal properties hold. In particular, |
680 |
* the cancel method itself must not throw exceptions. |
681 |
* |
682 |
* <p> This method is designed to be invoked by <em>other</em> |
683 |
* tasks. To terminate the current task, you can just return or |
684 |
* throw an unchecked exception from its computation method, or |
685 |
* invoke {@code completeExceptionally}. |
686 |
* |
687 |
* @param mayInterruptIfRunning this value is ignored in the |
688 |
* default implementation because tasks are not in general |
689 |
* cancelled via interruption |
690 |
* |
691 |
* @return true if this task is now cancelled |
692 |
*/ |
693 |
public boolean cancel(boolean mayInterruptIfRunning) { |
694 |
setCompletion(CANCELLED); |
695 |
return (status & COMPLETION_MASK) == CANCELLED; |
696 |
} |
697 |
|
698 |
/** |
699 |
* Returns true if this task threw an exception or was cancelled. |
700 |
* |
701 |
* @return true if this task threw an exception or was cancelled |
702 |
*/ |
703 |
public final boolean isCompletedAbnormally() { |
704 |
return (status & COMPLETION_MASK) < NORMAL; |
705 |
} |
706 |
|
707 |
/** |
708 |
* Returns the exception thrown by the base computation, or a |
709 |
* CancellationException if cancelled, or null if none or if the |
710 |
* method has not yet completed. |
711 |
* |
712 |
* @return the exception, or null if none |
713 |
*/ |
714 |
public final Throwable getException() { |
715 |
int s = status & COMPLETION_MASK; |
716 |
if (s >= NORMAL) |
717 |
return null; |
718 |
if (s == CANCELLED) |
719 |
return new CancellationException(); |
720 |
return exceptionMap.get(this); |
721 |
} |
722 |
|
723 |
/** |
724 |
* Completes this task abnormally, and if not already aborted or |
725 |
* cancelled, causes it to throw the given exception upon |
726 |
* {@code join} and related operations. This method may be used |
727 |
* to induce exceptions in asynchronous tasks, or to force |
728 |
* completion of tasks that would not otherwise complete. Its use |
729 |
* in other situations is likely to be wrong. This method is |
730 |
* overridable, but overridden versions must invoke {@code super} |
731 |
* implementation to maintain guarantees. |
732 |
* |
733 |
* @param ex the exception to throw. If this exception is |
734 |
* not a RuntimeException or Error, the actual exception thrown |
735 |
* will be a RuntimeException with cause ex. |
736 |
*/ |
737 |
public void completeExceptionally(Throwable ex) { |
738 |
setDoneExceptionally((ex instanceof RuntimeException) || |
739 |
(ex instanceof Error) ? ex : |
740 |
new RuntimeException(ex)); |
741 |
} |
742 |
|
743 |
/** |
744 |
* Completes this task, and if not already aborted or cancelled, |
745 |
* returning a {@code null} result upon {@code join} and related |
746 |
* operations. This method may be used to provide results for |
747 |
* asynchronous tasks, or to provide alternative handling for |
748 |
* tasks that would not otherwise complete normally. Its use in |
749 |
* other situations is likely to be wrong. This method is |
750 |
* overridable, but overridden versions must invoke {@code super} |
751 |
* implementation to maintain guarantees. |
752 |
* |
753 |
* @param value the result value for this task |
754 |
*/ |
755 |
public void complete(V value) { |
756 |
try { |
757 |
setRawResult(value); |
758 |
} catch (Throwable rex) { |
759 |
setDoneExceptionally(rex); |
760 |
return; |
761 |
} |
762 |
setNormalCompletion(); |
763 |
} |
764 |
|
765 |
public final V get() throws InterruptedException, ExecutionException { |
766 |
ForkJoinWorkerThread w = getWorker(); |
767 |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
768 |
awaitDone(w, true); |
769 |
return reportFutureResult(); |
770 |
} |
771 |
|
772 |
public final V get(long timeout, TimeUnit unit) |
773 |
throws InterruptedException, ExecutionException, TimeoutException { |
774 |
ForkJoinWorkerThread w = getWorker(); |
775 |
if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke()) |
776 |
awaitDone(w, unit.toNanos(timeout)); |
777 |
return reportTimedFutureResult(); |
778 |
} |
779 |
|
780 |
/** |
781 |
* Possibly executes other tasks until this task is ready, then |
782 |
* returns the result of the computation. This method may be more |
783 |
* efficient than {@code join}, but is only applicable when |
784 |
* there are no potential dependencies between continuation of the |
785 |
* current task and that of any other task that might be executed |
786 |
* while helping. (This usually holds for pure divide-and-conquer |
787 |
* tasks). This method may be invoked only from within |
788 |
* ForkJoinTask computations (as may be determined using method |
789 |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
790 |
* result in exceptions or errors, possibly including |
791 |
* ClassCastException. |
792 |
* |
793 |
* @return the computed result |
794 |
*/ |
795 |
public final V helpJoin() { |
796 |
ForkJoinWorkerThread w = (ForkJoinWorkerThread) Thread.currentThread(); |
797 |
if (status < 0 || !w.unpushTask(this) || !tryExec()) |
798 |
reportException(busyJoin(w)); |
799 |
return getRawResult(); |
800 |
} |
801 |
|
802 |
/** |
803 |
* Possibly executes other tasks until this task is ready. This |
804 |
* method may be invoked only from within ForkJoinTask |
805 |
* computations (as may be determined using method {@link |
806 |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
807 |
* in exceptions or errors, possibly including ClassCastException. |
808 |
*/ |
809 |
public final void quietlyHelpJoin() { |
810 |
if (status >= 0) { |
811 |
ForkJoinWorkerThread w = |
812 |
(ForkJoinWorkerThread) Thread.currentThread(); |
813 |
if (!w.unpushTask(this) || !tryQuietlyInvoke()) |
814 |
busyJoin(w); |
815 |
} |
816 |
} |
817 |
|
818 |
/** |
819 |
* Joins this task, without returning its result or throwing an |
820 |
* exception. This method may be useful when processing |
821 |
* collections of tasks when some have been cancelled or otherwise |
822 |
* known to have aborted. |
823 |
*/ |
824 |
public final void quietlyJoin() { |
825 |
if (status >= 0) { |
826 |
ForkJoinWorkerThread w = getWorker(); |
827 |
if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke()) |
828 |
awaitDone(w, true); |
829 |
} |
830 |
} |
831 |
|
832 |
/** |
833 |
* Commences performing this task and awaits its completion if |
834 |
* necessary, without returning its result or throwing an |
835 |
* exception. This method may be useful when processing |
836 |
* collections of tasks when some have been cancelled or otherwise |
837 |
* known to have aborted. |
838 |
*/ |
839 |
public final void quietlyInvoke() { |
840 |
if (status >= 0 && !tryQuietlyInvoke()) |
841 |
quietlyJoin(); |
842 |
} |
843 |
|
844 |
/** |
845 |
* Possibly executes tasks until the pool hosting the current task |
846 |
* {@link ForkJoinPool#isQuiescent}. This method may be of use in |
847 |
* designs in which many tasks are forked, but none are explicitly |
848 |
* joined, instead executing them until all are processed. |
849 |
*/ |
850 |
public static void helpQuiesce() { |
851 |
((ForkJoinWorkerThread) Thread.currentThread()) |
852 |
.helpQuiescePool(); |
853 |
} |
854 |
|
855 |
/** |
856 |
* Resets the internal bookkeeping state of this task, allowing a |
857 |
* subsequent {@code fork}. This method allows repeated reuse of |
858 |
* this task, but only if reuse occurs when this task has either |
859 |
* never been forked, or has been forked, then completed and all |
860 |
* outstanding joins of this task have also completed. Effects |
861 |
* under any other usage conditions are not guaranteed, and are |
862 |
* almost surely wrong. This method may be useful when executing |
863 |
* pre-constructed trees of subtasks in loops. |
864 |
*/ |
865 |
public void reinitialize() { |
866 |
if ((status & COMPLETION_MASK) == EXCEPTIONAL) |
867 |
exceptionMap.remove(this); |
868 |
status = 0; |
869 |
} |
870 |
|
871 |
/** |
872 |
* Returns the pool hosting the current task execution, or null |
873 |
* if this task is executing outside of any ForkJoinPool. |
874 |
* |
875 |
* @return the pool, or null if none |
876 |
*/ |
877 |
public static ForkJoinPool getPool() { |
878 |
Thread t = Thread.currentThread(); |
879 |
return (t instanceof ForkJoinWorkerThread) ? |
880 |
((ForkJoinWorkerThread) t).pool : null; |
881 |
} |
882 |
|
883 |
/** |
884 |
* Returns {@code true} if the current thread is executing as a |
885 |
* ForkJoinPool computation. |
886 |
* |
887 |
* @return {@code true} if the current thread is executing as a |
888 |
* ForkJoinPool computation, or false otherwise |
889 |
*/ |
890 |
public static boolean inForkJoinPool() { |
891 |
return Thread.currentThread() instanceof ForkJoinWorkerThread; |
892 |
} |
893 |
|
894 |
/** |
895 |
* Tries to unschedule this task for execution. This method will |
896 |
* typically succeed if this task is the most recently forked task |
897 |
* by the current thread, and has not commenced executing in |
898 |
* another thread. This method may be useful when arranging |
899 |
* alternative local processing of tasks that could have been, but |
900 |
* were not, stolen. This method may be invoked only from within |
901 |
* ForkJoinTask computations (as may be determined using method |
902 |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
903 |
* result in exceptions or errors, possibly including |
904 |
* ClassCastException. |
905 |
* |
906 |
* @return true if unforked |
907 |
*/ |
908 |
public boolean tryUnfork() { |
909 |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
910 |
.unpushTask(this); |
911 |
} |
912 |
|
913 |
/** |
914 |
* Returns an estimate of the number of tasks that have been |
915 |
* forked by the current worker thread but not yet executed. This |
916 |
* value may be useful for heuristic decisions about whether to |
917 |
* fork other tasks. |
918 |
* |
919 |
* @return the number of tasks |
920 |
*/ |
921 |
public static int getQueuedTaskCount() { |
922 |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
923 |
.getQueueSize(); |
924 |
} |
925 |
|
926 |
/** |
927 |
* Returns an estimate of how many more locally queued tasks are |
928 |
* held by the current worker thread than there are other worker |
929 |
* threads that might steal them. This value may be useful for |
930 |
* heuristic decisions about whether to fork other tasks. In many |
931 |
* usages of ForkJoinTasks, at steady state, each worker should |
932 |
* aim to maintain a small constant surplus (for example, 3) of |
933 |
* tasks, and to process computations locally if this threshold is |
934 |
* exceeded. |
935 |
* |
936 |
* @return the surplus number of tasks, which may be negative |
937 |
*/ |
938 |
public static int getSurplusQueuedTaskCount() { |
939 |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
940 |
.getEstimatedSurplusTaskCount(); |
941 |
} |
942 |
|
943 |
// Extension methods |
944 |
|
945 |
/** |
946 |
* Returns the result that would be returned by {@code join}, |
947 |
* even if this task completed abnormally, or null if this task is |
948 |
* not known to have been completed. This method is designed to |
949 |
* aid debugging, as well as to support extensions. Its use in any |
950 |
* other context is discouraged. |
951 |
* |
952 |
* @return the result, or null if not completed |
953 |
*/ |
954 |
public abstract V getRawResult(); |
955 |
|
956 |
/** |
957 |
* Forces the given value to be returned as a result. This method |
958 |
* is designed to support extensions, and should not in general be |
959 |
* called otherwise. |
960 |
* |
961 |
* @param value the value |
962 |
*/ |
963 |
protected abstract void setRawResult(V value); |
964 |
|
965 |
/** |
966 |
* Immediately performs the base action of this task. This method |
967 |
* is designed to support extensions, and should not in general be |
968 |
* called otherwise. The return value controls whether this task |
969 |
* is considered to be done normally. It may return false in |
970 |
* asynchronous actions that require explicit invocations of |
971 |
* {@code complete} to become joinable. It may throw exceptions |
972 |
* to indicate abnormal exit. |
973 |
* |
974 |
* @return true if completed normally |
975 |
* @throws Error or RuntimeException if encountered during computation |
976 |
*/ |
977 |
protected abstract boolean exec(); |
978 |
|
979 |
/** |
980 |
* Returns, but does not unschedule or execute, the task queued by |
981 |
* the current thread but not yet executed, if one is |
982 |
* available. There is no guarantee that this task will actually |
983 |
* be polled or executed next. This method is designed primarily |
984 |
* to support extensions, and is unlikely to be useful otherwise. |
985 |
* This method may be invoked only from within ForkJoinTask |
986 |
* computations (as may be determined using method {@link |
987 |
* #inForkJoinPool}). Attempts to invoke in other contexts result |
988 |
* in exceptions or errors, possibly including ClassCastException. |
989 |
* |
990 |
* @return the next task, or null if none are available |
991 |
*/ |
992 |
protected static ForkJoinTask<?> peekNextLocalTask() { |
993 |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
994 |
.peekTask(); |
995 |
} |
996 |
|
997 |
/** |
998 |
* Unschedules and returns, without executing, the next task |
999 |
* queued by the current thread but not yet executed. This method |
1000 |
* is designed primarily to support extensions, and is unlikely to |
1001 |
* be useful otherwise. This method may be invoked only from |
1002 |
* within ForkJoinTask computations (as may be determined using |
1003 |
* method {@link #inForkJoinPool}). Attempts to invoke in other |
1004 |
* contexts result in exceptions or errors, possibly including |
1005 |
* ClassCastException. |
1006 |
* |
1007 |
* @return the next task, or null if none are available |
1008 |
*/ |
1009 |
protected static ForkJoinTask<?> pollNextLocalTask() { |
1010 |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1011 |
.pollLocalTask(); |
1012 |
} |
1013 |
|
1014 |
/** |
1015 |
* Unschedules and returns, without executing, the next task |
1016 |
* queued by the current thread but not yet executed, if one is |
1017 |
* available, or if not available, a task that was forked by some |
1018 |
* other thread, if available. Availability may be transient, so a |
1019 |
* {@code null} result does not necessarily imply quiescence |
1020 |
* of the pool this task is operating in. This method is designed |
1021 |
* primarily to support extensions, and is unlikely to be useful |
1022 |
* otherwise. This method may be invoked only from within |
1023 |
* ForkJoinTask computations (as may be determined using method |
1024 |
* {@link #inForkJoinPool}). Attempts to invoke in other contexts |
1025 |
* result in exceptions or errors, possibly including |
1026 |
* ClassCastException. |
1027 |
* |
1028 |
* @return a task, or null if none are available |
1029 |
*/ |
1030 |
protected static ForkJoinTask<?> pollTask() { |
1031 |
return ((ForkJoinWorkerThread) Thread.currentThread()) |
1032 |
.pollTask(); |
1033 |
} |
1034 |
|
1035 |
// Serialization support |
1036 |
|
1037 |
private static final long serialVersionUID = -7721805057305804111L; |
1038 |
|
1039 |
/** |
1040 |
* Save the state to a stream. |
1041 |
* |
1042 |
* @serialData the current run status and the exception thrown |
1043 |
* during execution, or null if none |
1044 |
* @param s the stream |
1045 |
*/ |
1046 |
private void writeObject(java.io.ObjectOutputStream s) |
1047 |
throws java.io.IOException { |
1048 |
s.defaultWriteObject(); |
1049 |
s.writeObject(getException()); |
1050 |
} |
1051 |
|
1052 |
/** |
1053 |
* Reconstitute the instance from a stream. |
1054 |
* |
1055 |
* @param s the stream |
1056 |
*/ |
1057 |
private void readObject(java.io.ObjectInputStream s) |
1058 |
throws java.io.IOException, ClassNotFoundException { |
1059 |
s.defaultReadObject(); |
1060 |
status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts |
1061 |
status |= EXTERNAL_SIGNAL; // conservatively set external signal |
1062 |
Object ex = s.readObject(); |
1063 |
if (ex != null) |
1064 |
setDoneExceptionally((Throwable) ex); |
1065 |
} |
1066 |
|
1067 |
|
1068 |
// Unsafe mechanics |
1069 |
private static long fieldOffset(String fieldName, Class<?> klazz) { |
1070 |
try { |
1071 |
return UNSAFE.objectFieldOffset(klazz.getDeclaredField(fieldName)); |
1072 |
} catch (NoSuchFieldException e) { |
1073 |
// Convert Exception to Error |
1074 |
NoSuchFieldError error = new NoSuchFieldError(fieldName); |
1075 |
error.initCause(e); |
1076 |
throw error; |
1077 |
} |
1078 |
} |
1079 |
|
1080 |
private static final sun.misc.Unsafe UNSAFE = sun.misc.Unsafe.getUnsafe(); |
1081 |
static final long statusOffset = |
1082 |
fieldOffset("status", ForkJoinTask.class); |
1083 |
|
1084 |
} |