ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/ForkJoinTask.java
Revision: 1.13
Committed: Thu Jun 30 14:17:04 2016 UTC (7 years, 11 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.12: +1 -1 lines
Log Message:
fix typo reported by Ivan Gerasimov

File Contents

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