ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/ForkJoinTask.java
Revision: 1.59
Committed: Mon Feb 20 18:20:02 2012 UTC (12 years, 3 months ago) by dl
Branch: MAIN
Changes since 1.58: +154 -175 lines
Log Message:
less conservative compensation

File Contents

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