ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jsr166y/ForkJoinTask.java
(Generate patch)

Comparing jsr166/src/jsr166y/ForkJoinTask.java (file contents):
Revision 1.1 by dl, Tue Jan 6 14:30:31 2009 UTC vs.
Revision 1.13 by dl, Wed Jul 22 19:04:11 2009 UTC

# Line 13 | Line 13 | import sun.misc.Unsafe;
13   import java.lang.reflect.*;
14  
15   /**
16 < * Abstract base class for tasks that run within a ForkJoinPool.  A
17 < * ForkJoinTask is a thread-like entity that is much lighter weight
18 < * than a normal thread.  Huge numbers of tasks and subtasks may be
19 < * hosted by a small number of actual threads in a ForkJoinPool,
20 < * at the price of some usage limitations.
16 > * Abstract base class for tasks that run within a {@link
17 > * ForkJoinPool}.  A ForkJoinTask is a thread-like entity that is much
18 > * lighter weight than a normal thread.  Huge numbers of tasks and
19 > * subtasks may be hosted by a small number of actual threads in a
20 > * ForkJoinPool, at the price of some usage limitations.
21   *
22 < * <p> ForkJoinTasks are forms of <tt>Futures</tt> supporting a
23 < * limited range of use.  The "lightness" of ForkJoinTasks is due to a
24 < * set of restrictions (that are only partially statically
25 < * enforceable) reflecting their intended use as computational tasks
26 < * calculating pure functions or operating on purely isolated objects.
27 < * The primary coordination mechanisms supported for ForkJoinTasks are
28 < * <tt>fork</tt>, that arranges asynchronous execution, and
29 < * <tt>join</tt>, that doesn't proceed until the task's result has
30 < * been computed. (Cancellation is also supported).  The computation
31 < * defined in the <tt>compute</tt> method should avoid
32 < * <tt>synchronized</tt> methods or blocks, and should minimize
33 < * blocking synchronization apart from joining other tasks or using
22 > * <p> A "main" ForkJoinTask begins execution when submitted to a
23 > * {@link ForkJoinPool}. Once started, it will usually in turn start
24 > * other subtasks.  As indicated by the name of this class, many
25 > * programs using ForkJoinTasks employ only methods {@code fork}
26 > * and {@code join}, or derivatives such as
27 > * {@code invokeAll}.  However, this class also provides a number
28 > * of other methods that can come into play in advanced usages, as
29 > * well as extension mechanics that allow support of new forms of
30 > * fork/join processing.
31 > *
32 > * <p>A ForkJoinTask is a lightweight form of {@link Future}.  The
33 > * efficiency of ForkJoinTasks stems from a set of restrictions (that
34 > * are only partially statically enforceable) reflecting their
35 > * intended use as computational tasks calculating pure functions or
36 > * operating on purely isolated objects.  The primary coordination
37 > * mechanisms are {@link #fork}, that arranges asynchronous execution,
38 > * and {@link #join}, that doesn't proceed until the task's result has
39 > * been computed.  Computations should avoid {@code synchronized}
40 > * methods or blocks, and should minimize other blocking
41 > * synchronization apart from joining other tasks or using
42   * synchronizers such as Phasers that are advertised to cooperate with
43   * fork/join scheduling. Tasks should also not perform blocking IO,
44   * and should ideally access variables that are completely independent
# Line 38 | Line 46 | import java.lang.reflect.*;
46   * restrictions, for example using shared output streams, may be
47   * tolerable in practice, but frequent use may result in poor
48   * performance, and the potential to indefinitely stall if the number
49 < * of threads not waiting for external synchronization becomes
50 < * exhausted. This usage restriction is in part enforced by not
51 < * permitting checked exceptions such as IOExceptions to be
52 < * thrown. However, computations may still encounter unchecked
49 > * of threads not waiting for IO or other external synchronization
50 > * becomes exhausted. This usage restriction is in part enforced by
51 > * not permitting checked exceptions such as {@code IOExceptions}
52 > * to be thrown. However, computations may still encounter unchecked
53   * exceptions, that are rethrown to callers attempting join
54   * them. These exceptions may additionally include
55   * RejectedExecutionExceptions stemming from internal resource
56   * exhaustion such as failure to allocate internal task queues.
57   *
58 < * <p> The <tt>ForkJoinTask</tt> class is not usually directly
59 < * subclassed.  Instead, you subclass one of the abstract classes that
60 < * support different styles of fork/join processing.  Normally, a
61 < * concrete ForkJoinTask subclass declares fields comprising its
62 < * parameters, established in a constructor, and then defines a
63 < * <tt>compute</tt> method that somehow uses the control methods
64 < * supplied by this base class. While these methods have
65 < * <tt>public</tt> access, some of them may only be called from within
66 < * other ForkJoinTasks. Attempts to invoke them in other contexts
67 < * result in exceptions or errors including ClassCastException.  The
68 < * only way to invoke a "main" driver task is to submit it to a
69 < * ForkJoinPool. Once started, this will usually in turn start other
70 < * subtasks.
58 > * <p>The primary method for awaiting completion and extracting
59 > * results of a task is {@link #join}, but there are several variants:
60 > * The {@link Future#get} methods support interruptible and/or timed
61 > * waits for completion and report results using {@code Future}
62 > * conventions. Method {@link #helpJoin} enables callers to actively
63 > * execute other tasks while awaiting joins, which is sometimes more
64 > * efficient but only applies when all subtasks are known to be
65 > * strictly tree-structured. Method {@link #invoke} is semantically
66 > * equivalent to {@code fork(); join()} but always attempts to
67 > * begin execution in the current thread. The "<em>quiet</em>" forms
68 > * of these methods do not extract results or report exceptions. These
69 > * may be useful when a set of tasks are being executed, and you need
70 > * to delay processing of results or exceptions until all complete.
71 > * Method {@code invokeAll} (available in multiple versions)
72 > * performs the most common form of parallel invocation: forking a set
73 > * of tasks and joining them all.
74 > *
75 > * <p> The ForkJoinTask class is not usually directly subclassed.
76 > * Instead, you subclass one of the abstract classes that support a
77 > * particular style of fork/join processing.  Normally, a concrete
78 > * ForkJoinTask subclass declares fields comprising its parameters,
79 > * established in a constructor, and then defines a {@code compute}
80 > * method that somehow uses the control methods supplied by this base
81 > * class. While these methods have {@code public} access (to allow
82 > * instances of different task subclasses to call each others
83 > * methods), some of them may only be called from within other
84 > * ForkJoinTasks (as may be determined using method {@link
85 > * #inForkJoinPool}).  Attempts to invoke them in other contexts
86 > * result in exceptions or errors possibly including
87 > * ClassCastException.
88   *
89 < * <p>Most base support methods are <tt>final</tt> because their
89 > * <p>Most base support methods are {@code final} because their
90   * implementations are intrinsically tied to the underlying
91   * lightweight task scheduling framework, and so cannot be overridden.
92   * Developers creating new basic styles of fork/join processing should
93 < * minimally implement protected methods <tt>exec</tt>,
94 < * <tt>setRawResult</tt>, and <tt>getRawResult</tt>, while also
95 < * introducing an abstract computational method that can be
96 < * implemented in its subclasses. To support such extensions,
97 < * instances of ForkJoinTasks maintain an atomically updated
98 < * <tt>short</tt> representing user-defined control state.  Control
74 < * state is guaranteed initially to be zero, and to be negative upon
75 < * completion, but may otherwise be used for any other control
76 < * purposes, such as maintaining join counts.  The {@link
77 < * ForkJoinWorkerThread} class supports additional inspection and
78 < * tuning methods that can be useful when developing extensions.
93 > * minimally implement {@code protected} methods
94 > * {@code exec}, {@code setRawResult}, and
95 > * {@code getRawResult}, while also introducing an abstract
96 > * computational method that can be implemented in its subclasses,
97 > * possibly relying on other {@code protected} methods provided
98 > * by this class.
99   *
100   * <p>ForkJoinTasks should perform relatively small amounts of
101 < * computations, othewise splitting into smaller tasks. As a very
101 > * computations, otherwise splitting into smaller tasks. As a very
102   * rough rule of thumb, a task should perform more than 100 and less
103   * than 10000 basic computational steps. If tasks are too big, then
104 < * parellelism cannot improve throughput. If too small, then memory
104 > * parallelism cannot improve throughput. If too small, then memory
105   * and internal task maintenance overhead may overwhelm processing.
106   *
107 < * <p>ForkJoinTasks are <tt>Serializable</tt>, which enables them to
108 < * be used in extensions such as remote execution frameworks. However,
109 < * it is in general safe to serialize tasks only before or after, but
107 > * <p>ForkJoinTasks are {@code Serializable}, which enables them
108 > * to be used in extensions such as remote execution frameworks. It is
109 > * in general sensible to serialize tasks only before or after, but
110   * not during execution. Serialization is not relied on during
111   * execution itself.
112 + *
113 + * @since 1.7
114 + * @author Doug Lea
115   */
116   public abstract class ForkJoinTask<V> implements Future<V>, Serializable {
117 +
118      /**
119 <     * Status field holding all run status. We pack this into a single
120 <     * int both to minimize footprint overhead and to ensure atomicity
121 <     * (updates are via CAS).
98 <     *
99 <     * Status is initially zero, and takes on nonnegative values until
119 >     * Run control status bits packed into a single int to minimize
120 >     * footprint and to ensure atomicity (via CAS).  Status is
121 >     * initially zero, and takes on nonnegative values until
122       * completed, upon which status holds COMPLETED. CANCELLED, or
123       * EXCEPTIONAL, which use the top 3 bits.  Tasks undergoing
124       * blocking waits by other threads have SIGNAL_MASK bits set --
# Line 111 | Line 133 | public abstract class ForkJoinTask<V> im
133       * currently unused. Also value 0x80000000 is available as spare
134       * completion value.
135       */
136 <    volatile int status; // accessed directy by pool and workers
136 >    volatile int status; // accessed directly by pool and workers
137  
138      static final int COMPLETION_MASK      = 0xe0000000;
139      static final int NORMAL               = 0xe0000000; // == mask
# Line 124 | Line 146 | public abstract class ForkJoinTask<V> im
146      /**
147       * Table of exceptions thrown by tasks, to enable reporting by
148       * callers. Because exceptions are rare, we don't directly keep
149 <     * them with task objects, but instead us a weak ref table.  Note
149 >     * them with task objects, but instead use a weak ref table.  Note
150       * that cancellation exceptions don't appear in the table, but are
151       * instead recorded as status values.
152 <     * Todo: Use ConcurrentReferenceHashMap
152 >     * TODO: Use ConcurrentReferenceHashMap
153       */
154      static final Map<ForkJoinTask<?>, Throwable> exceptionMap =
155          Collections.synchronizedMap
# Line 136 | Line 158 | public abstract class ForkJoinTask<V> im
158      // within-package utilities
159  
160      /**
161 <     * Get current worker thread, or null if not a worker thread
161 >     * Gets current worker thread, or null if not a worker thread.
162       */
163      static ForkJoinWorkerThread getWorker() {
164          Thread t = Thread.currentThread();
# Line 144 | Line 166 | public abstract class ForkJoinTask<V> im
166                  (ForkJoinWorkerThread)t : null);
167      }
168  
147    /**
148     * Get pool of current worker thread, or null if not a worker thread
149     */
150    static ForkJoinPool getWorkerPool() {
151        Thread t = Thread.currentThread();
152        return ((t instanceof ForkJoinWorkerThread)?
153                ((ForkJoinWorkerThread)t).pool : null);
154    }
155
169      final boolean casStatus(int cmp, int val) {
170 <        return _unsafe.compareAndSwapInt(this, statusOffset, cmp, val);
170 >        return UNSAFE.compareAndSwapInt(this, statusOffset, cmp, val);
171      }
172  
173      /**
# Line 162 | Line 175 | public abstract class ForkJoinTask<V> im
175       */
176      static void rethrowException(Throwable ex) {
177          if (ex != null)
178 <            _unsafe.throwException(ex);
178 >            UNSAFE.throwException(ex);
179      }
180  
181      // Setting completion status
182  
183      /**
184 <     * Mark completion and wake up threads waiting to join this task.
184 >     * Marks completion and wakes up threads waiting to join this task.
185 >     *
186       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
187       */
188      final void setCompletion(int completion) {
189 <        ForkJoinPool pool = getWorkerPool();
189 >        ForkJoinPool pool = getPool();
190          if (pool != null) {
191              int s; // Clear signal bits while setting completion status
192              do;while ((s = status) >= 0 && !casStatus(s, completion));
# Line 204 | Line 218 | public abstract class ForkJoinTask<V> im
218      final void setNormalCompletion() {
219          // Try typical fast case -- single CAS, no signal, not already done.
220          // Manually expand casStatus to improve chances of inlining it
221 <        if (!_unsafe.compareAndSwapInt(this, statusOffset, 0, NORMAL))
221 >        if (!UNSAFE.compareAndSwapInt(this, statusOffset, 0, NORMAL))
222              setCompletion(NORMAL);
223      }
224  
# Line 247 | Line 261 | public abstract class ForkJoinTask<V> im
261      /**
262       * Sets status to indicate there is joiner, then waits for join,
263       * surrounded with pool notifications.
264 +     *
265       * @return status upon exit
266       */
267 <    final int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
267 >    private int awaitDone(ForkJoinWorkerThread w, boolean maintainParallelism) {
268          ForkJoinPool pool = w == null? null : w.pool;
269          int s;
270          while ((s = status) >= 0) {
# Line 268 | Line 283 | public abstract class ForkJoinTask<V> im
283       * Timed version of awaitDone
284       * @return status upon exit
285       */
286 <    final int awaitDone(ForkJoinWorkerThread w, long nanos) {
286 >    private int awaitDone(ForkJoinWorkerThread w, long nanos) {
287          ForkJoinPool pool = w == null? null : w.pool;
288          int s;
289          while ((s = status) >= 0) {
# Line 289 | Line 304 | public abstract class ForkJoinTask<V> im
304      }
305  
306      /**
307 <     * Notify pool that thread is unblocked. Called by signalled
307 >     * Notifies pool that thread is unblocked. Called by signalled
308       * threads when woken by non-FJ threads (which is atypical).
309       */
310      private void adjustPoolCountsOnUnblock(ForkJoinPool pool) {
# Line 300 | Line 315 | public abstract class ForkJoinTask<V> im
315      }
316  
317      /**
318 <     * Notify pool to adjust counts on cancelled or timed out wait
318 >     * Notifies pool to adjust counts on cancelled or timed out wait.
319       */
320      private void adjustPoolCountsOnCancelledWait(ForkJoinPool pool) {
321          if (pool != null) {
# Line 314 | Line 329 | public abstract class ForkJoinTask<V> im
329          }
330      }
331  
332 +    /**
333 +     * Handles interruptions during waits.
334 +     */
335      private void onInterruptedWait() {
336 <        Thread t = Thread.currentThread();
337 <        if (t instanceof ForkJoinWorkerThread) {
338 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread)t;
339 <            if (w.isTerminating())
340 <                cancelIgnoreExceptions();
341 <        }
324 <        else { // re-interrupt
325 <            try {
326 <                t.interrupt();
327 <            } catch (SecurityException ignore) {
328 <            }
329 <        }
336 >        ForkJoinWorkerThread w = getWorker();
337 >        if (w == null)
338 >            Thread.currentThread().interrupt(); // re-interrupt
339 >        else if (w.isTerminating())
340 >            cancelIgnoringExceptions();
341 >        // else if FJworker, ignore interrupt
342      }
343  
344      // Recording and reporting exceptions
# Line 337 | Line 349 | public abstract class ForkJoinTask<V> im
349      }
350  
351      /**
352 <     * Throws the exception associated with status s;
352 >     * Throws the exception associated with status s.
353 >     *
354       * @throws the exception
355       */
356      private void reportException(int s) {
# Line 350 | Line 363 | public abstract class ForkJoinTask<V> im
363      }
364  
365      /**
366 <     * Returns result or throws exception using j.u.c.Future conventions
366 >     * Returns result or throws exception using j.u.c.Future conventions.
367       * Only call when isDone known to be true.
368       */
369      private V reportFutureResult()
# Line 370 | Line 383 | public abstract class ForkJoinTask<V> im
383  
384      /**
385       * Returns result or throws exception using j.u.c.Future conventions
386 <     * with timeouts
386 >     * with timeouts.
387       */
388      private V reportTimedFutureResult()
389          throws InterruptedException, ExecutionException, TimeoutException {
# Line 391 | Line 404 | public abstract class ForkJoinTask<V> im
404  
405      /**
406       * Calls exec, recording completion, and rethrowing exception if
407 <     * encountered. Caller should normally check status before calling
407 >     * encountered. Caller should normally check status before calling.
408 >     *
409       * @return true if completed normally
410       */
411      private boolean tryExec() {
# Line 409 | Line 423 | public abstract class ForkJoinTask<V> im
423  
424      /**
425       * Main execution method used by worker threads. Invokes
426 <     * base computation unless already complete
426 >     * base computation unless already complete.
427       */
428      final void quietlyExec() {
429          if (status >= 0) {
# Line 425 | Line 439 | public abstract class ForkJoinTask<V> im
439      }
440  
441      /**
442 <     * Calls exec, recording but not rethrowing exception
443 <     * Caller should normally check status before calling
442 >     * Calls exec(), recording but not rethrowing exception.
443 >     * Caller should normally check status before calling.
444 >     *
445       * @return true if completed normally
446       */
447      private boolean tryQuietlyInvoke() {
# Line 442 | Line 457 | public abstract class ForkJoinTask<V> im
457      }
458  
459      /**
460 <     * Cancel, ignoring any exceptions it throws
460 >     * Cancels, ignoring any exceptions it throws.
461       */
462 <    final void cancelIgnoreExceptions() {
462 >    final void cancelIgnoringExceptions() {
463          try {
464              cancel(false);
465          } catch(Throwable ignore) {
466          }
467      }
468  
469 +    /**
470 +     * Main implementation of helpJoin
471 +     */
472 +    private int busyJoin(ForkJoinWorkerThread w) {
473 +        int s;
474 +        ForkJoinTask<?> t;
475 +        while ((s = status) >= 0 && (t = w.scanWhileJoining(this)) != null)
476 +            t.quietlyExec();
477 +        return (s >= 0)? awaitDone(w, false) : s; // block if no work
478 +    }
479 +
480      // public methods
481  
482      /**
483       * Arranges to asynchronously execute this task.  While it is not
484       * necessarily enforced, it is a usage error to fork a task more
485       * than once unless it has completed and been reinitialized.  This
486 <     * method may be invoked only from within other ForkJoinTask
487 <     * computations. Attempts to invoke in other contexts result in
488 <     * exceptions or errors including ClassCastException.
486 >     * method may be invoked only from within ForkJoinTask
487 >     * computations (as may be determined using method {@link
488 >     * #inForkJoinPool}). Attempts to invoke in other contexts result
489 >     * in exceptions or errors possibly including ClassCastException.
490       */
491      public final void fork() {
492          ((ForkJoinWorkerThread)(Thread.currentThread())).pushTask(this);
# Line 467 | Line 494 | public abstract class ForkJoinTask<V> im
494  
495      /**
496       * Returns the result of the computation when it is ready.
497 <     * This method differs from <tt>get</tt> in that abnormal
497 >     * This method differs from {@code get} in that abnormal
498       * completion results in RuntimeExceptions or Errors, not
499       * ExecutionExceptions.
500       *
# Line 480 | Line 507 | public abstract class ForkJoinTask<V> im
507          return getRawResult();
508      }
509  
483    public final V get() throws InterruptedException, ExecutionException {
484        ForkJoinWorkerThread w = getWorker();
485        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
486            awaitDone(w, true);
487        return reportFutureResult();
488    }
489
490    public final V get(long timeout, TimeUnit unit)
491        throws InterruptedException, ExecutionException, TimeoutException {
492        ForkJoinWorkerThread w = getWorker();
493        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
494            awaitDone(w, unit.toNanos(timeout));
495        return reportTimedFutureResult();
496    }
497
510      /**
511 <     * Possibly executes other tasks until this task is ready, then
512 <     * returns the result of the computation.  This method may be more
513 <     * efficient than <tt>join</tt>, but is only applicable when there
502 <     * are no potemtial dependencies between continuation of the
503 <     * current task and that of any other task that might be executed
504 <     * while helping. (This usually holds for pure divide-and-conquer
505 <     * tasks).
506 <     * @return the computed result
507 <     */
508 <    public final V helpJoin() {
509 <        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
510 <        if (status < 0 || !w.unpushTask(this) || !tryExec())
511 <            reportException(w.helpJoinTask(this));
512 <        return getRawResult();
513 <    }
514 <
515 <    /**
516 <     * Performs this task, awaits its completion if necessary, and
517 <     * return its result.
511 >     * Commences performing this task, awaits its completion if
512 >     * necessary, and return its result.
513 >     *
514       * @throws Throwable (a RuntimeException, Error, or unchecked
515 <     * exception) if the underlying computation did so.
515 >     * exception) if the underlying computation did so
516       * @return the computed result
517       */
518      public final V invoke() {
# Line 527 | Line 523 | public abstract class ForkJoinTask<V> im
523      }
524  
525      /**
526 <     * Joins this task, without returning its result or throwing an
527 <     * exception. This method may be useful when processing
528 <     * collections of tasks when some have been cancelled or otherwise
529 <     * known to have aborted.
526 >     * Forks both tasks, returning when {@code isDone} holds for
527 >     * both of them or an exception is encountered. This method may be
528 >     * invoked only from within ForkJoinTask computations (as may be
529 >     * determined using method {@link #inForkJoinPool}). Attempts to
530 >     * invoke in other contexts result in exceptions or errors
531 >     * possibly including ClassCastException.
532 >     *
533 >     * @param t1 one task
534 >     * @param t2 the other task
535 >     * @throws NullPointerException if t1 or t2 are null
536 >     * @throws RuntimeException or Error if either task did so
537       */
538 <    public final void quietlyJoin() {
539 <        if (status >= 0) {
540 <            ForkJoinWorkerThread w = getWorker();
541 <            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
539 <                awaitDone(w, true);
540 <        }
538 >    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
539 >        t2.fork();
540 >        t1.invoke();
541 >        t2.join();
542      }
543  
544      /**
545 <     * Possibly executes other tasks until this task is ready.
545 >     * Forks the given tasks, returning when {@code isDone} holds
546 >     * for all of them. If any task encounters an exception, others
547 >     * may be cancelled.  This method may be invoked only from within
548 >     * ForkJoinTask computations (as may be determined using method
549 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
550 >     * result in exceptions or errors possibly including
551 >     * ClassCastException.
552 >     * @param tasks the array of tasks
553 >     * @throws NullPointerException if tasks or any element are null
554 >     * @throws RuntimeException or Error if any task did so
555       */
556 <    public final void quietlyHelpJoin() {
557 <        if (status >= 0) {
558 <            ForkJoinWorkerThread w =
559 <                (ForkJoinWorkerThread)(Thread.currentThread());
560 <            if (!w.unpushTask(this) || !tryQuietlyInvoke())
561 <                w.helpJoinTask(this);
556 >    public static void invokeAll(ForkJoinTask<?>... tasks) {
557 >        Throwable ex = null;
558 >        int last = tasks.length - 1;
559 >        for (int i = last; i >= 0; --i) {
560 >            ForkJoinTask<?> t = tasks[i];
561 >            if (t == null) {
562 >                if (ex == null)
563 >                    ex = new NullPointerException();
564 >            }
565 >            else if (i != 0)
566 >                t.fork();
567 >            else {
568 >                t.quietlyInvoke();
569 >                if (ex == null)
570 >                    ex = t.getException();
571 >            }
572 >        }
573 >        for (int i = 1; i <= last; ++i) {
574 >            ForkJoinTask<?> t = tasks[i];
575 >            if (t != null) {
576 >                if (ex != null)
577 >                    t.cancel(false);
578 >                else {
579 >                    t.quietlyJoin();
580 >                    if (ex == null)
581 >                        ex = t.getException();
582 >                }
583 >            }
584          }
585 +        if (ex != null)
586 +            rethrowException(ex);
587      }
588  
589      /**
590 <     * Performs this task and awaits its completion if necessary,
591 <     * without returning its result or throwing an exception. This
592 <     * method may be useful when processing collections of tasks when
593 <     * some have been cancelled or otherwise known to have aborted.
590 >     * Forks all tasks in the collection, returning when
591 >     * {@code isDone} holds for all of them. If any task
592 >     * encounters an exception, others may be cancelled.  This method
593 >     * may be invoked only from within ForkJoinTask computations (as
594 >     * may be determined using method {@link
595 >     * #inForkJoinPool}). Attempts to invoke in other contexts resul!t
596 >     * in exceptions or errors possibly including ClassCastException.
597 >     *
598 >     * @param tasks the collection of tasks
599 >     * @throws NullPointerException if tasks or any element are null
600 >     * @throws RuntimeException or Error if any task did so
601       */
602 <    public final void quietlyInvoke() {
603 <        if (status >= 0 && !tryQuietlyInvoke())
604 <            quietlyJoin();
602 >    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
603 >        if (!(tasks instanceof List)) {
604 >            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
605 >            return;
606 >        }
607 >        List<? extends ForkJoinTask<?>> ts =
608 >            (List<? extends ForkJoinTask<?>>)tasks;
609 >        Throwable ex = null;
610 >        int last = ts.size() - 1;
611 >        for (int i = last; i >= 0; --i) {
612 >            ForkJoinTask<?> t = ts.get(i);
613 >            if (t == null) {
614 >                if (ex == null)
615 >                    ex = new NullPointerException();
616 >            }
617 >            else if (i != 0)
618 >                t.fork();
619 >            else {
620 >                t.quietlyInvoke();
621 >                if (ex == null)
622 >                    ex = t.getException();
623 >            }
624 >        }
625 >        for (int i = 1; i <= last; ++i) {
626 >            ForkJoinTask<?> t = ts.get(i);
627 >            if (t != null) {
628 >                if (ex != null)
629 >                    t.cancel(false);
630 >                else {
631 >                    t.quietlyJoin();
632 >                    if (ex == null)
633 >                        ex = t.getException();
634 >                }
635 >            }
636 >        }
637 >        if (ex != null)
638 >            rethrowException(ex);
639      }
640  
641      /**
642       * Returns true if the computation performed by this task has
643       * completed (or has been cancelled).
644 +     *
645       * @return true if this computation has completed
646       */
647      public final boolean isDone() {
# Line 574 | Line 650 | public abstract class ForkJoinTask<V> im
650  
651      /**
652       * Returns true if this task was cancelled.
653 +     *
654       * @return true if this task was cancelled
655       */
656      public final boolean isCancelled() {
# Line 581 | Line 658 | public abstract class ForkJoinTask<V> im
658      }
659  
660      /**
584     * Returns true if this task threw an exception or was cancelled
585     * @return true if this task threw an exception or was cancelled
586     */
587    public final boolean completedAbnormally() {
588        return (status & COMPLETION_MASK) < NORMAL;
589    }
590
591    /**
592     * Returns the exception thrown by the base computation, or a
593     * CancellationException if cancelled, or null if none or if the
594     * method has not yet completed.
595     * @return the exception, or null if none
596     */
597    public final Throwable getException() {
598        int s = status & COMPLETION_MASK;
599        if (s >= NORMAL)
600            return null;
601        if (s == CANCELLED)
602            return new CancellationException();
603        return exceptionMap.get(this);
604    }
605
606    /**
661       * Asserts that the results of this task's computation will not be
662 <     * used. If a cancellation occurs before this task is processed,
663 <     * then its <tt>compute</tt> method will not be executed,
664 <     * <tt>isCancelled</tt> will report true, and <tt>join</tt> will
665 <     * result in a CancellationException being thrown. Otherwise, when
662 >     * used. If a cancellation occurs before attempting to execute this
663 >     * task, then execution will be suppressed, {@code isCancelled}
664 >     * will report true, and {@code join} will result in a
665 >     * {@code CancellationException} being thrown. Otherwise, when
666       * cancellation races with completion, there are no guarantees
667 <     * about whether <tt>isCancelled</tt> will report true, whether
668 <     * <tt>join</tt> will return normally or via an exception, or
667 >     * about whether {@code isCancelled} will report true, whether
668 >     * {@code join} will return normally or via an exception, or
669       * whether these behaviors will remain consistent upon repeated
670       * invocation.
671       *
# Line 622 | Line 676 | public abstract class ForkJoinTask<V> im
676       * <p> This method is designed to be invoked by <em>other</em>
677       * tasks. To terminate the current task, you can just return or
678       * throw an unchecked exception from its computation method, or
679 <     * invoke <tt>completeExceptionally(someException)</tt>.
679 >     * invoke {@code completeExceptionally}.
680       *
681       * @param mayInterruptIfRunning this value is ignored in the
682       * default implementation because tasks are not in general
# Line 636 | Line 690 | public abstract class ForkJoinTask<V> im
690      }
691  
692      /**
693 +     * Returns true if this task threw an exception or was cancelled.
694 +     *
695 +     * @return true if this task threw an exception or was cancelled
696 +     */
697 +    public final boolean isCompletedAbnormally() {
698 +        return (status & COMPLETION_MASK) < NORMAL;
699 +    }
700 +
701 +    /**
702 +     * Returns the exception thrown by the base computation, or a
703 +     * CancellationException if cancelled, or null if none or if the
704 +     * method has not yet completed.
705 +     *
706 +     * @return the exception, or null if none
707 +     */
708 +    public final Throwable getException() {
709 +        int s = status & COMPLETION_MASK;
710 +        if (s >= NORMAL)
711 +            return null;
712 +        if (s == CANCELLED)
713 +            return new CancellationException();
714 +        return exceptionMap.get(this);
715 +    }
716 +
717 +    /**
718       * Completes this task abnormally, and if not already aborted or
719       * cancelled, causes it to throw the given exception upon
720 <     * <tt>join</tt> and related operations. This method may be used
720 >     * {@code join} and related operations. This method may be used
721       * to induce exceptions in asynchronous tasks, or to force
722 <     * completion of tasks that would not otherwise complete.  This
723 <     * method is overridable, but overridden versions must invoke
724 <     * <tt>super</tt> implementation to maintain guarantees.
722 >     * completion of tasks that would not otherwise complete.  Its use
723 >     * in other situations is likely to be wrong.  This method is
724 >     * overridable, but overridden versions must invoke {@code super}
725 >     * implementation to maintain guarantees.
726 >     *
727       * @param ex the exception to throw. If this exception is
728       * not a RuntimeException or Error, the actual exception thrown
729       * will be a RuntimeException with cause ex.
# Line 655 | Line 736 | public abstract class ForkJoinTask<V> im
736  
737      /**
738       * Completes this task, and if not already aborted or cancelled,
739 <     * returning a <tt>null</tt> result upon <tt>join</tt> and related
739 >     * returning a {@code null} result upon {@code join} and related
740       * operations. This method may be used to provide results for
741       * asynchronous tasks, or to provide alternative handling for
742 <     * tasks that would not otherwise complete normally.
742 >     * tasks that would not otherwise complete normally. Its use in
743 >     * other situations is likely to be wrong. This method is
744 >     * overridable, but overridden versions must invoke {@code super}
745 >     * implementation to maintain guarantees.
746       *
747 <     * @param value the result value for this task.
747 >     * @param value the result value for this task
748       */
749      public void complete(V value) {
750          try {
# Line 672 | Line 756 | public abstract class ForkJoinTask<V> im
756          setNormalCompletion();
757      }
758  
759 +    public final V get() throws InterruptedException, ExecutionException {
760 +        ForkJoinWorkerThread w = getWorker();
761 +        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
762 +            awaitDone(w, true);
763 +        return reportFutureResult();
764 +    }
765 +
766 +    public final V get(long timeout, TimeUnit unit)
767 +        throws InterruptedException, ExecutionException, TimeoutException {
768 +        ForkJoinWorkerThread w = getWorker();
769 +        if (w == null || status < 0 || !w.unpushTask(this) || !tryQuietlyInvoke())
770 +            awaitDone(w, unit.toNanos(timeout));
771 +        return reportTimedFutureResult();
772 +    }
773 +
774 +    /**
775 +     * Possibly executes other tasks until this task is ready, then
776 +     * returns the result of the computation.  This method may be more
777 +     * efficient than {@code join}, but is only applicable when
778 +     * there are no potential dependencies between continuation of the
779 +     * current task and that of any other task that might be executed
780 +     * while helping. (This usually holds for pure divide-and-conquer
781 +     * tasks). This method may be invoked only from within
782 +     * ForkJoinTask computations (as may be determined using method
783 +     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
784 +     * resul!t in exceptions or errors possibly including
785 +     * ClassCastException.
786 +     *
787 +     * @return the computed result
788 +     */
789 +    public final V helpJoin() {
790 +        ForkJoinWorkerThread w = (ForkJoinWorkerThread)(Thread.currentThread());
791 +        if (status < 0 || !w.unpushTask(this) || !tryExec())
792 +            reportException(busyJoin(w));
793 +        return getRawResult();
794 +    }
795 +
796 +    /**
797 +     * Possibly executes other tasks until this task is ready.  This
798 +     * method may be invoked only from within ForkJoinTask
799 +     * computations (as may be determined using method {@link
800 +     * #inForkJoinPool}). Attempts to invoke in other contexts resul!t
801 +     * in exceptions or errors possibly including ClassCastException.
802 +     */
803 +    public final void quietlyHelpJoin() {
804 +        if (status >= 0) {
805 +            ForkJoinWorkerThread w =
806 +                (ForkJoinWorkerThread)(Thread.currentThread());
807 +            if (!w.unpushTask(this) || !tryQuietlyInvoke())
808 +                busyJoin(w);
809 +        }
810 +    }
811 +
812 +    /**
813 +     * Joins this task, without returning its result or throwing an
814 +     * exception. This method may be useful when processing
815 +     * collections of tasks when some have been cancelled or otherwise
816 +     * known to have aborted.
817 +     */
818 +    public final void quietlyJoin() {
819 +        if (status >= 0) {
820 +            ForkJoinWorkerThread w = getWorker();
821 +            if (w == null || !w.unpushTask(this) || !tryQuietlyInvoke())
822 +                awaitDone(w, true);
823 +        }
824 +    }
825 +
826 +    /**
827 +     * Commences performing this task and awaits its completion if
828 +     * necessary, without returning its result or throwing an
829 +     * exception. This method may be useful when processing
830 +     * collections of tasks when some have been cancelled or otherwise
831 +     * known to have aborted.
832 +     */
833 +    public final void quietlyInvoke() {
834 +        if (status >= 0 && !tryQuietlyInvoke())
835 +            quietlyJoin();
836 +    }
837 +
838 +    /**
839 +     * Possibly executes tasks until the pool hosting the current task
840 +     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
841 +     * designs in which many tasks are forked, but none are explicitly
842 +     * joined, instead executing them until all are processed.
843 +     */
844 +    public static void helpQuiesce() {
845 +        ((ForkJoinWorkerThread)(Thread.currentThread())).
846 +            helpQuiescePool();
847 +    }
848 +
849      /**
850       * Resets the internal bookkeeping state of this task, allowing a
851 <     * subsequent <tt>fork</tt>. This method allows repeated reuse of
851 >     * subsequent {@code fork}. This method allows repeated reuse of
852       * this task, but only if reuse occurs when this task has either
853       * never been forked, or has been forked, then completed and all
854       * outstanding joins of this task have also completed. Effects
# Line 689 | Line 863 | public abstract class ForkJoinTask<V> im
863      }
864  
865      /**
866 <     * Tries to unschedule this task for execution. This method will
867 <     * typically succeed if this task is the next task that would be
868 <     * executed by the current thread, and will typically fail (return
869 <     * false) otherwise. This method may be useful when arranging
696 <     * faster local processing of tasks that could have been, but were
697 <     * not, stolen.
698 <     * @return true if unforked
866 >     * Returns the pool hosting the current task execution, or null
867 >     * if this task is executing outside of any ForkJoinPool.
868 >     *
869 >     * @return the pool, or null if none.
870       */
871 <    public boolean tryUnfork() {
872 <        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
871 >    public static ForkJoinPool getPool() {
872 >        Thread t = Thread.currentThread();
873 >        return ((t instanceof ForkJoinWorkerThread)?
874 >                ((ForkJoinWorkerThread)t).pool : null);
875      }
876  
877      /**
878 <     * Forks both tasks, returning when <tt>isDone</tt> holds for both
879 <     * of them or an exception is encountered. This method may be
880 <     * invoked only from within other ForkJoinTask
881 <     * computations. Attempts to invoke in other contexts result in
709 <     * exceptions or errors including ClassCastException.
710 <     * @param t1 one task
711 <     * @param t2 the other task
712 <     * @throws NullPointerException if t1 or t2 are null
713 <     * @throws RuntimeException or Error if either task did so.
878 >     * Returns true if the current thread is executing as a
879 >     * ForkJoinPool computation.
880 >     * @return <code>true</code> if the current thread is executing as a
881 >     * ForkJoinPool computation, or false otherwise
882       */
883 <    public static void invokeAll(ForkJoinTask<?>t1, ForkJoinTask<?> t2) {
884 <        t2.fork();
717 <        t1.invoke();
718 <        t2.join();
883 >    public static boolean inForkJoinPool() {
884 >        return Thread.currentThread() instanceof ForkJoinWorkerThread;
885      }
886  
887      /**
888 <     * Forks the given tasks, returning when <tt>isDone</tt> holds for
889 <     * all of them. If any task encounters an exception, others may be
890 <     * cancelled.  This method may be invoked only from within other
891 <     * ForkJoinTask computations. Attempts to invoke in other contexts
892 <     * result in exceptions or errors including ClassCastException.
893 <     * @param tasks the array of tasks
894 <     * @throws NullPointerException if tasks or any element are null.
895 <     * @throws RuntimeException or Error if any task did so.
896 <     */
897 <    public static void invokeAll(ForkJoinTask<?>... tasks) {
898 <        Throwable ex = null;
899 <        int last = tasks.length - 1;
734 <        for (int i = last; i >= 0; --i) {
735 <            ForkJoinTask<?> t = tasks[i];
736 <            if (t == null) {
737 <                if (ex == null)
738 <                    ex = new NullPointerException();
739 <            }
740 <            else if (i != 0)
741 <                t.fork();
742 <            else {
743 <                t.quietlyInvoke();
744 <                if (ex == null)
745 <                    ex = t.getException();
746 <            }
747 <        }
748 <        for (int i = 1; i <= last; ++i) {
749 <            ForkJoinTask<?> t = tasks[i];
750 <            if (t != null) {
751 <                if (ex != null)
752 <                    t.cancel(false);
753 <                else {
754 <                    t.quietlyJoin();
755 <                    if (ex == null)
756 <                        ex = t.getException();
757 <                }
758 <            }
759 <        }
760 <        if (ex != null)
761 <            rethrowException(ex);
762 <    }
763 <
764 <    /**
765 <     * Forks all tasks in the collection, returning when
766 <     * <tt>isDone</tt> holds for all of them. If any task encounters
767 <     * an exception, others may be cancelled.  This method may be
768 <     * invoked only from within other ForkJoinTask
769 <     * computations. Attempts to invoke in other contexts result in
770 <     * exceptions or errors including ClassCastException.
771 <     * @param tasks the collection of tasks
772 <     * @throws NullPointerException if tasks or any element are null.
773 <     * @throws RuntimeException or Error if any task did so.
888 >     * Tries to unschedule this task for execution. This method will
889 >     * typically succeed if this task is the most recently forked task
890 >     * by the current thread, and has not commenced executing in
891 >     * another thread.  This method may be useful when arranging
892 >     * alternative local processing of tasks that could have been, but
893 >     * were not, stolen. This method may be invoked only from within
894 >     * ForkJoinTask computations (as may be determined using method
895 >     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
896 >     * result in exceptions or errors possibly including
897 >     * ClassCastException.
898 >     *
899 >     * @return true if unforked
900       */
901 <    public static void invokeAll(Collection<? extends ForkJoinTask<?>> tasks) {
902 <        if (!(tasks instanceof List)) {
777 <            invokeAll(tasks.toArray(new ForkJoinTask[tasks.size()]));
778 <            return;
779 <        }
780 <        List<? extends ForkJoinTask<?>> ts =
781 <            (List<? extends ForkJoinTask<?>>)tasks;
782 <        Throwable ex = null;
783 <        int last = ts.size() - 1;
784 <        for (int i = last; i >= 0; --i) {
785 <            ForkJoinTask<?> t = ts.get(i);
786 <            if (t == null) {
787 <                if (ex == null)
788 <                    ex = new NullPointerException();
789 <            }
790 <            else if (i != 0)
791 <                t.fork();
792 <            else {
793 <                t.quietlyInvoke();
794 <                if (ex == null)
795 <                    ex = t.getException();
796 <            }
797 <        }
798 <        for (int i = 1; i <= last; ++i) {
799 <            ForkJoinTask<?> t = ts.get(i);
800 <            if (t != null) {
801 <                if (ex != null)
802 <                    t.cancel(false);
803 <                else {
804 <                    t.quietlyJoin();
805 <                    if (ex == null)
806 <                        ex = t.getException();
807 <                }
808 <            }
809 <        }
810 <        if (ex != null)
811 <            rethrowException(ex);
901 >    public boolean tryUnfork() {
902 >        return ((ForkJoinWorkerThread)(Thread.currentThread())).unpushTask(this);
903      }
904  
905      /**
906 <     * Possibly executes tasks until the pool hosting the current task
907 <     * {@link ForkJoinPool#isQuiescent}. This method may be of use in
908 <     * designs in which many tasks are forked, but none are explicitly
909 <     * joined, instead executing them until all are processed.
906 >     * Returns an estimate of the number of tasks that have been
907 >     * forked by the current worker thread but not yet executed. This
908 >     * value may be useful for heuristic decisions about whether to
909 >     * fork other tasks.
910 >     *
911 >     * @return the number of tasks
912       */
913 <    public static void helpQuiesce() {
914 <        ((ForkJoinWorkerThread)(Thread.currentThread())).
915 <            helpQuiescePool();
913 >    public static int getQueuedTaskCount() {
914 >        return ((ForkJoinWorkerThread)(Thread.currentThread())).
915 >            getQueueSize();
916      }
917  
918      /**
919 <     * Returns a estimate of how many more locally queued tasks are
919 >     * Returns an estimate of how many more locally queued tasks are
920       * held by the current worker thread than there are other worker
921 <     * threads that might want to steal them.  This value may be
922 <     * useful for heuristic decisions about whether to fork other
923 <     * tasks. In many usages of ForkJoinTasks, at steady state, each
924 <     * worker should aim to maintain a small constant surplus (for
925 <     * example, 3) of tasks, and to process computations locally if
926 <     * this threshold is exceeded.
921 >     * threads that might steal them.  This value may be useful for
922 >     * heuristic decisions about whether to fork other tasks. In many
923 >     * usages of ForkJoinTasks, at steady state, each worker should
924 >     * aim to maintain a small constant surplus (for example, 3) of
925 >     * tasks, and to process computations locally if this threshold is
926 >     * exceeded.
927 >     *
928       * @return the surplus number of tasks, which may be negative
929       */
930 <    public static int surplus() {
930 >    public static int getSurplusQueuedTaskCount() {
931          return ((ForkJoinWorkerThread)(Thread.currentThread()))
932              .getEstimatedSurplusTaskCount();
933      }
934  
935 <    // Extension kit
935 >    // Extension methods
936  
937      /**
938 <     * Returns the result that would be returned by <tt>join</tt>, or
939 <     * null if this task is not known to have been completed.  This
940 <     * method is designed to aid debugging, as well as to support
941 <     * extensions. Its use in any other context is discouraged.
938 >     * Returns the result that would be returned by {@code join},
939 >     * even if this task completed abnormally, or null if this task is
940 >     * not known to have been completed.  This method is designed to
941 >     * aid debugging, as well as to support extensions. Its use in any
942 >     * other context is discouraged.
943       *
944 <     * @return the result, or null if not completed.
944 >     * @return the result, or null if not completed
945       */
946      public abstract V getRawResult();
947  
# Line 865 | Line 960 | public abstract class ForkJoinTask<V> im
960       * called otherwise. The return value controls whether this task
961       * is considered to be done normally. It may return false in
962       * asynchronous actions that require explicit invocations of
963 <     * <tt>complete</tt> to become joinable. It may throw exceptions
963 >     * {@code complete} to become joinable. It may throw exceptions
964       * to indicate abnormal exit.
965 +     *
966       * @return true if completed normally
967       * @throws Error or RuntimeException if encountered during computation
968       */
969      protected abstract boolean exec();
970  
971 +    /**
972 +     * Returns, but does not unschedule or execute, the task queued by
973 +     * the current thread but not yet executed, if one is
974 +     * available. There is no guarantee that this task will actually
975 +     * be polled or executed next.  This method is designed primarily
976 +     * to support extensions, and is unlikely to be useful otherwise.
977 +     * This method may be invoked only from within ForkJoinTask
978 +     * computations (as may be determined using method {@link
979 +     * #inForkJoinPool}). Attempts to invoke in other contexts result
980 +     * in exceptions or errors possibly including ClassCastException.
981 +     *
982 +     * @return the next task, or null if none are available
983 +     */
984 +    protected static ForkJoinTask<?> peekNextLocalTask() {
985 +        return ((ForkJoinWorkerThread)(Thread.currentThread())).peekTask();
986 +    }
987 +
988 +    /**
989 +     * Unschedules and returns, without executing, the next task
990 +     * queued by the current thread but not yet executed.  This method
991 +     * is designed primarily to support extensions, and is unlikely to
992 +     * be useful otherwise.  This method may be invoked only from
993 +     * within ForkJoinTask computations (as may be determined using
994 +     * method {@link #inForkJoinPool}). Attempts to invoke in other
995 +     * contexts result in exceptions or errors possibly including
996 +     * ClassCastException.
997 +     *
998 +     * @return the next task, or null if none are available
999 +     */
1000 +    protected static ForkJoinTask<?> pollNextLocalTask() {
1001 +        return ((ForkJoinWorkerThread)(Thread.currentThread())).pollLocalTask();
1002 +    }
1003 +
1004 +    /**
1005 +     * Unschedules and returns, without executing, the next task
1006 +     * queued by the current thread but not yet executed, if one is
1007 +     * available, or if not available, a task that was forked by some
1008 +     * other thread, if available. Availability may be transient, so a
1009 +     * {@code null} result does not necessarily imply quiescence
1010 +     * of the pool this task is operating in.  This method is designed
1011 +     * primarily to support extensions, and is unlikely to be useful
1012 +     * otherwise.  This method may be invoked only from within
1013 +     * ForkJoinTask computations (as may be determined using method
1014 +     * {@link #inForkJoinPool}). Attempts to invoke in other contexts
1015 +     * result in exceptions or errors possibly including
1016 +     * ClassCastException.
1017 +     *
1018 +     * @return a task, or null if none are available
1019 +     */
1020 +    protected static ForkJoinTask<?> pollTask() {
1021 +        return ((ForkJoinWorkerThread)(Thread.currentThread())).
1022 +            pollTask();
1023 +    }
1024 +
1025      // Serialization support
1026  
1027      private static final long serialVersionUID = -7721805057305804111L;
# Line 880 | Line 1030 | public abstract class ForkJoinTask<V> im
1030       * Save the state to a stream.
1031       *
1032       * @serialData the current run status and the exception thrown
1033 <     * during execution, or null if none.
1033 >     * during execution, or null if none
1034       * @param s the stream
1035       */
1036      private void writeObject(java.io.ObjectOutputStream s)
# Line 891 | Line 1041 | public abstract class ForkJoinTask<V> im
1041  
1042      /**
1043       * Reconstitute the instance from a stream.
1044 +     *
1045       * @param s the stream
1046       */
1047      private void readObject(java.io.ObjectInputStream s)
1048          throws java.io.IOException, ClassNotFoundException {
1049          s.defaultReadObject();
1050 <        //        status &= ~INTERNAL_SIGNAL_MASK; //  todo: define policy
1050 >        status &= ~INTERNAL_SIGNAL_MASK; // clear internal signal counts
1051 >        status |= EXTERNAL_SIGNAL; // conservatively set external signal
1052          Object ex = s.readObject();
1053          if (ex != null)
1054              setDoneExceptionally((Throwable)ex);
1055      }
1056  
1057      // Temporary Unsafe mechanics for preliminary release
1058 +    private static Unsafe getUnsafe() throws Throwable {
1059 +        try {
1060 +            return Unsafe.getUnsafe();
1061 +        } catch (SecurityException se) {
1062 +            try {
1063 +                return java.security.AccessController.doPrivileged
1064 +                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
1065 +                        public Unsafe run() throws Exception {
1066 +                            return getUnsafePrivileged();
1067 +                        }});
1068 +            } catch (java.security.PrivilegedActionException e) {
1069 +                throw e.getCause();
1070 +            }
1071 +        }
1072 +    }
1073 +
1074 +    private static Unsafe getUnsafePrivileged()
1075 +            throws NoSuchFieldException, IllegalAccessException {
1076 +        Field f = Unsafe.class.getDeclaredField("theUnsafe");
1077 +        f.setAccessible(true);
1078 +        return (Unsafe) f.get(null);
1079 +    }
1080 +
1081 +    private static long fieldOffset(String fieldName)
1082 +            throws NoSuchFieldException {
1083 +        return UNSAFE.objectFieldOffset
1084 +            (ForkJoinTask.class.getDeclaredField(fieldName));
1085 +    }
1086  
1087 <    static final Unsafe _unsafe;
1087 >    static final Unsafe UNSAFE;
1088      static final long statusOffset;
1089  
1090      static {
1091          try {
1092 <            if (ForkJoinTask.class.getClassLoader() != null) {
1093 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
1094 <                f.setAccessible(true);
1095 <                _unsafe = (Unsafe)f.get(null);
1096 <            }
917 <            else
918 <                _unsafe = Unsafe.getUnsafe();
919 <            statusOffset = _unsafe.objectFieldOffset
920 <                (ForkJoinTask.class.getDeclaredField("status"));
921 <        } catch (Exception ex) { throw new Error(ex); }
1092 >            UNSAFE = getUnsafe();
1093 >            statusOffset = fieldOffset("status");
1094 >        } catch (Throwable e) {
1095 >            throw new RuntimeException("Could not initialize intrinsics", e);
1096 >        }
1097      }
1098  
1099   }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines