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.74 by dl, Tue Feb 22 00:39:31 2011 UTC vs.
Revision 1.86 by dl, Mon Feb 20 18:20:06 2012 UTC

# Line 1 | Line 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/licenses/publicdomain
4 > * http://creativecommons.org/publicdomain/zero/1.0/
5   */
6  
7   package jsr166y;
8
8   import java.io.Serializable;
9   import java.util.Collection;
11 import java.util.Collections;
10   import java.util.List;
11   import java.util.RandomAccess;
14 import java.util.Map;
12   import java.lang.ref.WeakReference;
13   import java.lang.ref.ReferenceQueue;
14   import java.util.concurrent.Callable;
15   import java.util.concurrent.CancellationException;
16   import java.util.concurrent.ExecutionException;
20 import java.util.concurrent.Executor;
21 import java.util.concurrent.ExecutorService;
17   import java.util.concurrent.Future;
18   import java.util.concurrent.RejectedExecutionException;
19   import java.util.concurrent.RunnableFuture;
# Line 47 | Line 42 | import java.lang.reflect.Constructor;
42   * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
43   * The efficiency of {@code ForkJoinTask}s stems from a set of
44   * restrictions (that are only partially statically enforceable)
45 < * reflecting their intended use as computational tasks calculating
46 < * pure functions or operating on purely isolated objects.  The
47 < * primary coordination mechanisms are {@link #fork}, that arranges
45 > * reflecting their main use as computational tasks calculating pure
46 > * functions or operating on purely isolated objects.  The primary
47 > * coordination mechanisms are {@link #fork}, that arranges
48   * asynchronous execution, and {@link #join}, that doesn't proceed
49   * until the task's result has been computed.  Computations should
50 < * avoid {@code synchronized} methods or blocks, and should minimize
51 < * other blocking synchronization apart from joining other tasks or
52 < * using synchronizers such as Phasers that are advertised to
53 < * cooperate with fork/join scheduling. Tasks should also not perform
54 < * blocking IO, and should ideally access variables that are
55 < * completely independent of those accessed by other running
56 < * tasks. Minor breaches of these restrictions, for example using
57 < * shared output streams, may be tolerable in practice, but frequent
58 < * use may result in poor performance, and the potential to
59 < * indefinitely stall if the number of threads not waiting for IO or
60 < * other external synchronization becomes exhausted. This usage
61 < * restriction is in part enforced by not permitting checked
62 < * exceptions such as {@code IOExceptions} to be thrown. However,
63 < * computations may still encounter unchecked exceptions, that are
64 < * rethrown to callers attempting to join them. These exceptions may
65 < * additionally include {@link RejectedExecutionException} stemming
66 < * from internal resource exhaustion, such as failure to allocate
67 < * internal task queues. Rethrown exceptions behave in the same way as
68 < * regular exceptions, but, when possible, contain stack traces (as
69 < * displayed for example using {@code ex.printStackTrace()}) of both
70 < * the thread that initiated the computation as well as the thread
71 < * actually encountering the exception; minimally only the latter.
50 > * ideally avoid {@code synchronized} methods or blocks, and should
51 > * minimize other blocking synchronization apart from joining other
52 > * tasks or using synchronizers such as Phasers that are advertised to
53 > * cooperate with fork/join scheduling. Subdividable tasks should also
54 > * not perform blocking IO, and should ideally access variables that
55 > * are completely independent of those accessed by other running
56 > * tasks. These guidelines are loosely enforced by not permitting
57 > * checked exceptions such as {@code IOExceptions} to be
58 > * thrown. However, computations may still encounter unchecked
59 > * exceptions, that are rethrown to callers attempting to join
60 > * them. These exceptions may additionally include {@link
61 > * RejectedExecutionException} stemming from internal resource
62 > * exhaustion, such as failure to allocate internal task
63 > * queues. Rethrown exceptions behave in the same way as regular
64 > * exceptions, but, when possible, contain stack traces (as displayed
65 > * for example using {@code ex.printStackTrace()}) of both the thread
66 > * that initiated the computation as well as the thread actually
67 > * encountering the exception; minimally only the latter.
68 > *
69 > * <p>It is possible to define and use ForkJoinTasks that may block,
70 > * but doing do requires three further considerations: (1) Completion
71 > * of few if any <em>other</em> tasks should be dependent on a task
72 > * that blocks on external synchronization or IO. Event-style async
73 > * tasks that are never joined often fall into this category.  (2) To
74 > * minimize resource impact, tasks should be small; ideally performing
75 > * only the (possibly) blocking action. (3) Unless the {@link
76 > * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
77 > * blocked tasks is known to be less than the pool's {@link
78 > * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
79 > * enough threads will be available to ensure progress or good
80 > * performance.
81   *
82   * <p>The primary method for awaiting completion and extracting
83   * results of a task is {@link #join}, but there are several variants:
# Line 89 | Line 93 | import java.lang.reflect.Constructor;
93   * performs the most common form of parallel invocation: forking a set
94   * of tasks and joining them all.
95   *
96 + * <p>In the most typical usages, a fork-join pair act like a call
97 + * (fork) and return (join) from a parallel recursive function. As is
98 + * the case with other forms of recursive calls, returns (joins)
99 + * should be performed innermost-first. For example, {@code a.fork();
100 + * b.fork(); b.join(); a.join();} is likely to be substantially more
101 + * efficient than joining {@code a} before {@code b}.
102 + *
103   * <p>The execution status of tasks may be queried at several levels
104   * of detail: {@link #isDone} is true if a task completed in any way
105   * (including the case where a task was cancelled without executing);
# Line 125 | Line 136 | import java.lang.reflect.Constructor;
136   * supports other methods and techniques (for example the use of
137   * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
138   * may be of use in constructing custom subclasses for problems that
139 < * are not statically structured as DAGs.
139 > * are not statically structured as DAGs. To support such usages a
140 > * ForkJoinTask may be atomically <em>marked</em> using {@link
141 > * #markForkJoinTask} and checked for marking using {@link
142 > * #isMarkedForkJoinTask}. The ForkJoinTask implementation does not
143 > * use these {@code protected} methods or marks for any purpose, but
144 > * they may be of use in the construction of specialized subclasses.
145 > * For example, parallel graph traversals can use the supplied methods
146 > * to avoid revisiting nodes/tasks that have already been processed.
147 > * Also, completion based designs can use them to record that one
148 > * subtask has completed. (Method names for marking are bulky in part
149 > * to encourage definition of methods that reflect their usage
150 > * patterns.)
151   *
152   * <p>Most base support methods are {@code final}, to prevent
153   * overriding of implementations that are intrinsically tied to the
# Line 165 | Line 187 | public abstract class ForkJoinTask<V> im
187       * See the internal documentation of class ForkJoinPool for a
188       * general implementation overview.  ForkJoinTasks are mainly
189       * responsible for maintaining their "status" field amidst relays
190 <     * to methods in ForkJoinWorkerThread and ForkJoinPool. The
191 <     * methods of this class are more-or-less layered into (1) basic
192 <     * status maintenance (2) execution and awaiting completion (3)
193 <     * user-level methods that additionally report results. This is
194 <     * sometimes hard to see because this file orders exported methods
195 <     * in a way that flows well in javadocs.
190 >     * to methods in ForkJoinWorkerThread and ForkJoinPool.
191 >     *
192 >     * The methods of this class are more-or-less layered into
193 >     * (1) basic status maintenance
194 >     * (2) execution and awaiting completion
195 >     * (3) user-level methods that additionally report results.
196 >     * This is sometimes hard to see because this file orders exported
197 >     * methods in a way that flows well in javadocs.
198       */
199  
200      /*
201       * The status field holds run control status bits packed into a
202       * single int to minimize footprint and to ensure atomicity (via
203       * CAS).  Status is initially zero, and takes on nonnegative
204 <     * values until completed, upon which status holds value
205 <     * NORMAL, CANCELLED, or EXCEPTIONAL. Tasks undergoing blocking
206 <     * waits by other threads have the SIGNAL bit set.  Completion of
207 <     * a stolen task with SIGNAL set awakens any waiters via
208 <     * notifyAll. Even though suboptimal for some purposes, we use
209 <     * basic builtin wait/notify to take advantage of "monitor
210 <     * inflation" in JVMs that we would otherwise need to emulate to
211 <     * avoid adding further per-task bookkeeping overhead.  We want
212 <     * these monitors to be "fat", i.e., not use biasing or thin-lock
213 <     * techniques, so use some odd coding idioms that tend to avoid
214 <     * them.
204 >     * values until completed, upon which status (anded with
205 >     * DONE_MASK) holds value NORMAL, CANCELLED, or EXCEPTIONAL. Tasks
206 >     * undergoing blocking waits by other threads have the SIGNAL bit
207 >     * set.  Completion of a stolen task with SIGNAL set awakens any
208 >     * waiters via notifyAll. Even though suboptimal for some
209 >     * purposes, we use basic builtin wait/notify to take advantage of
210 >     * "monitor inflation" in JVMs that we would otherwise need to
211 >     * emulate to avoid adding further per-task bookkeeping overhead.
212 >     * We want these monitors to be "fat", i.e., not use biasing or
213 >     * thin-lock techniques, so use some odd coding idioms that tend
214 >     * to avoid them, mainly by arranging that every synchronized
215 >     * block performs a wait, notifyAll or both.
216       */
217  
218      /** The run status of this task */
219      volatile int status; // accessed directly by pool and workers
220 <    private static final int NORMAL      = -1;
221 <    private static final int CANCELLED   = -2;
222 <    private static final int EXCEPTIONAL = -3;
223 <    private static final int SIGNAL      =  1;
220 >    static final int DONE_MASK   = 0xf0000000;  // mask out non-completion bits
221 >    static final int NORMAL      = 0xf0000000;  // must be negative
222 >    static final int CANCELLED   = 0xc0000000;  // must be < NORMAL
223 >    static final int EXCEPTIONAL = 0x80000000;  // must be < CANCELLED
224 >    static final int SIGNAL      = 0x00000001;
225 >    static final int MARKED      = 0x00000002;
226  
227      /**
228 <     * Marks completion and wakes up threads waiting to join this task,
229 <     * also clearing signal request bits.
228 >     * Marks completion and wakes up threads waiting to join this
229 >     * task. A specialization for NORMAL completion is in method
230 >     * doExec.
231       *
232       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
233       * @return completion status on exit
# Line 208 | Line 236 | public abstract class ForkJoinTask<V> im
236          for (int s;;) {
237              if ((s = status) < 0)
238                  return s;
239 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
240 <                if (s != 0)
239 >            if (U.compareAndSwapInt(this, STATUS, s, s | completion)) {
240 >                if ((s & SIGNAL) != 0)
241                      synchronized (this) { notifyAll(); }
242                  return completion;
243              }
# Line 217 | Line 245 | public abstract class ForkJoinTask<V> im
245      }
246  
247      /**
248 <     * Tries to block a worker thread until completed or timed out.
249 <     * Uses Object.wait time argument conventions.
250 <     * May fail on contention or interrupt.
248 >     * Primary execution method for stolen tasks. Unless done, calls
249 >     * exec and records status if completed, but doesn't wait for
250 >     * completion otherwise.
251       *
252 <     * @param millis if > 0, wait time.
252 >     * @return status on exit from this method
253       */
254 <    final void tryAwaitDone(long millis) {
255 <        int s;
256 <        try {
257 <            if (((s = status) > 0 ||
258 <                 (s == 0 &&
259 <                  UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
260 <                status > 0) {
261 <                synchronized (this) {
262 <                    if (status > 0)
263 <                        wait(millis);
254 >    final int doExec() {
255 >        int s; boolean completed;
256 >        if ((s = status) >= 0) {
257 >            try {
258 >                completed = exec();
259 >            } catch (Throwable rex) {
260 >                return setExceptionalCompletion(rex);
261 >            }
262 >            while ((s = status) >= 0 && completed) {
263 >                if (U.compareAndSwapInt(this, STATUS, s, s | NORMAL)) {
264 >                    if ((s & SIGNAL) != 0)
265 >                        synchronized (this) { notifyAll(); }
266 >                    return NORMAL;
267                  }
268              }
238        } catch (InterruptedException ie) {
239            // caller must check termination
269          }
270 +        return s;
271 +    }
272 +
273 +    /**
274 +     * Tries to set SIGNAL status. Used by ForkJoinPool. Other
275 +     * variants are directly incorporated into externalAwaitDone etc.
276 +     *
277 +     * @return true if successful
278 +     */
279 +    final boolean trySetSignal() {
280 +        int s;
281 +        return U.compareAndSwapInt(this, STATUS, s = status, s | SIGNAL);
282      }
283  
284      /**
# Line 245 | Line 286 | public abstract class ForkJoinTask<V> im
286       * @return status upon completion
287       */
288      private int externalAwaitDone() {
289 +        boolean interrupted = false;
290          int s;
291 <        if ((s = status) >= 0) {
292 <            boolean interrupted = false;
293 <            synchronized (this) {
294 <                while ((s = status) >= 0) {
253 <                    if (s == 0)
254 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
255 <                                                 0, SIGNAL);
256 <                    else {
291 >        while ((s = status) >= 0) {
292 >            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
293 >                synchronized (this) {
294 >                    if (status >= 0) {
295                          try {
296                              wait();
297                          } catch (InterruptedException ie) {
298                              interrupted = true;
299                          }
300                      }
301 +                    else
302 +                        notifyAll();
303                  }
304              }
265            if (interrupted)
266                Thread.currentThread().interrupt();
305          }
306 +        if (interrupted)
307 +            Thread.currentThread().interrupt();
308          return s;
309      }
310  
311      /**
312 <     * Blocks a non-worker-thread until completion or interruption or timeout.
312 >     * Blocks a non-worker-thread until completion or interruption.
313       */
314 <    private int externalInterruptibleAwaitDone(long millis)
275 <        throws InterruptedException {
314 >    private int externalInterruptibleAwaitDone() throws InterruptedException {
315          int s;
316          if (Thread.interrupted())
317              throw new InterruptedException();
318 <        if ((s = status) >= 0) {
319 <            synchronized (this) {
320 <                while ((s = status) >= 0) {
321 <                    if (s == 0)
322 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
284 <                                                 0, SIGNAL);
318 >        while ((s = status) >= 0) {
319 >            if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
320 >                synchronized (this) {
321 >                    if (status >= 0)
322 >                        wait();
323                      else
324 <                        wait(millis);
324 >                        notifyAll();
325                  }
326              }
327          }
328          return s;
329      }
330  
293    /**
294     * Primary execution method for stolen tasks. Unless done, calls
295     * exec and records status if completed, but doesn't wait for
296     * completion otherwise.
297     */
298    final void doExec() {
299        if (status >= 0) {
300            boolean completed;
301            try {
302                completed = exec();
303            } catch (Throwable rex) {
304                setExceptionalCompletion(rex);
305                return;
306            }
307            if (completed)
308                setCompletion(NORMAL); // must be outside try block
309        }
310    }
331  
332      /**
333 <     * Primary mechanics for join, get, quietlyJoin.
333 >     * Implementation for join, get, quietlyJoin. Directly handles
334 >     * only cases of already-completed, external wait, and
335 >     * unfork+exec.  Others are relayed to ForkJoinPool.awaitJoin.
336 >     *
337       * @return status upon completion
338       */
339      private int doJoin() {
340 <        Thread t; ForkJoinWorkerThread w; int s; boolean completed;
341 <        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
342 <            if ((s = status) < 0)
343 <                return s;
344 <            if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
345 <                try {
323 <                    completed = exec();
324 <                } catch (Throwable rex) {
325 <                    return setExceptionalCompletion(rex);
326 <                }
327 <                if (completed)
328 <                    return setCompletion(NORMAL);
340 >        int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
341 >        if ((s = status) >= 0) {
342 >            if (((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)) {
343 >                if (!(w = (wt = (ForkJoinWorkerThread)t).workQueue).
344 >                    tryUnpush(this) || (s = doExec()) >= 0)
345 >                    s = wt.pool.awaitJoin(w, this);
346              }
347 <            return w.joinTask(this);
347 >            else
348 >                s = externalAwaitDone();
349          }
350 <        else
333 <            return externalAwaitDone();
350 >        return s;
351      }
352  
353      /**
354 <     * Primary mechanics for invoke, quietlyInvoke.
354 >     * Implementation for invoke, quietlyInvoke.
355 >     *
356       * @return status upon completion
357       */
358      private int doInvoke() {
359 <        int s; boolean completed;
360 <        if ((s = status) < 0)
361 <            return s;
362 <        try {
363 <            completed = exec();
364 <        } catch (Throwable rex) {
365 <            return setExceptionalCompletion(rex);
359 >        int s; Thread t; ForkJoinWorkerThread wt;
360 >        if ((s = doExec()) >= 0) {
361 >            if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread)
362 >                s = (wt = (ForkJoinWorkerThread)t).pool.awaitJoin(wt.workQueue,
363 >                                                                  this);
364 >            else
365 >                s = externalAwaitDone();
366          }
367 <        if (completed)
350 <            return setCompletion(NORMAL);
351 <        else
352 <            return doJoin();
367 >        return s;
368      }
369  
370      // Exception table support
# Line 381 | Line 396 | public abstract class ForkJoinTask<V> im
396       * periods. However, since we do not know when the last joiner
397       * completes, we must use weak references and expunge them. We do
398       * so on each operation (hence full locking). Also, some thread in
399 <     * any ForkJoinPool will call helpExpunge when its pool becomes
400 <     * isQuiescent.
399 >     * any ForkJoinPool will call helpExpungeStaleExceptions when its
400 >     * pool becomes isQuiescent.
401       */
402 <    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
402 >    static final class ExceptionNode extends WeakReference<ForkJoinTask<?>> {
403          final Throwable ex;
404          ExceptionNode next;
405 <        final long thrower;
405 >        final long thrower;  // use id not ref to avoid weak cycles
406          ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
407              super(task, exceptionTableRefQueue);
408              this.ex = ex;
# Line 403 | Line 418 | public abstract class ForkJoinTask<V> im
418       */
419      private int setExceptionalCompletion(Throwable ex) {
420          int h = System.identityHashCode(this);
421 <        ReentrantLock lock = exceptionTableLock;
421 >        final ReentrantLock lock = exceptionTableLock;
422          lock.lock();
423          try {
424              expungeStaleExceptions();
# Line 424 | Line 439 | public abstract class ForkJoinTask<V> im
439      }
440  
441      /**
442 +     * Cancels, ignoring any exceptions thrown by cancel. Used during
443 +     * worker and pool shutdown. Cancel is spec'ed not to throw any
444 +     * exceptions, but if it does anyway, we have no recourse during
445 +     * shutdown, so guard against this case.
446 +     */
447 +    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
448 +        if (t != null && t.status >= 0) {
449 +            try {
450 +                t.cancel(false);
451 +            } catch (Throwable ignore) {
452 +            }
453 +        }
454 +    }
455 +
456 +    /**
457       * Removes exception node and clears status
458       */
459      private void clearExceptionalCompletion() {
460          int h = System.identityHashCode(this);
461 <        ReentrantLock lock = exceptionTableLock;
461 >        final ReentrantLock lock = exceptionTableLock;
462          lock.lock();
463          try {
464              ExceptionNode[] t = exceptionTable;
# Line 469 | Line 499 | public abstract class ForkJoinTask<V> im
499       * @return the exception, or null if none
500       */
501      private Throwable getThrowableException() {
502 <        if (status != EXCEPTIONAL)
502 >        if ((status & DONE_MASK) != EXCEPTIONAL)
503              return null;
504          int h = System.identityHashCode(this);
505          ExceptionNode e;
506 <        ReentrantLock lock = exceptionTableLock;
506 >        final ReentrantLock lock = exceptionTableLock;
507          lock.lock();
508          try {
509              expungeStaleExceptions();
# Line 488 | Line 518 | public abstract class ForkJoinTask<V> im
518          if (e == null || (ex = e.ex) == null)
519              return null;
520          if (e.thrower != Thread.currentThread().getId()) {
521 <            Class ec = ex.getClass();
521 >            Class<? extends Throwable> ec = ex.getClass();
522              try {
523                  Constructor<?> noArgCtor = null;
524                  Constructor<?>[] cs = ec.getConstructors();// public ctors only
# Line 539 | Line 569 | public abstract class ForkJoinTask<V> im
569      }
570  
571      /**
572 <     * If lock is available, poll any stale refs and remove them.
572 >     * If lock is available, poll stale refs and remove them.
573       * Called from ForkJoinPool when pools become quiescent.
574       */
575      static final void helpExpungeStaleExceptions() {
576 <        ReentrantLock lock = exceptionTableLock;
576 >        final ReentrantLock lock = exceptionTableLock;
577          if (lock.tryLock()) {
578              try {
579                  expungeStaleExceptions();
# Line 554 | Line 584 | public abstract class ForkJoinTask<V> im
584      }
585  
586      /**
587 <     * Report the result of invoke or join; called only upon
558 <     * non-normal return of internal versions.
587 >     * Throws exception, if any, associated with the given status.
588       */
589 <    private V reportResult() {
590 <        int s; Throwable ex;
591 <        if ((s = status) == CANCELLED)
592 <            throw new CancellationException();
593 <        if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
594 <            UNSAFE.throwException(ex);
566 <        return getRawResult();
589 >    private void reportException(int s) {
590 >        Throwable ex = ((s == CANCELLED) ?  new CancellationException() :
591 >                        (s == EXCEPTIONAL) ? getThrowableException() :
592 >                        null);
593 >        if (ex != null)
594 >            U.throwException(ex);
595      }
596  
597      // public methods
# Line 587 | Line 615 | public abstract class ForkJoinTask<V> im
615       * @return {@code this}, to simplify usage
616       */
617      public final ForkJoinTask<V> fork() {
618 <        ((ForkJoinWorkerThread) Thread.currentThread())
591 <            .pushTask(this);
618 >        ((ForkJoinWorkerThread)Thread.currentThread()).workQueue.push(this);
619          return this;
620      }
621  
# Line 604 | Line 631 | public abstract class ForkJoinTask<V> im
631       * @return the computed result
632       */
633      public final V join() {
634 <        if (doJoin() != NORMAL)
635 <            return reportResult();
636 <        else
637 <            return getRawResult();
634 >        int s;
635 >        if ((s = doJoin() & DONE_MASK) != NORMAL)
636 >            reportException(s);
637 >        return getRawResult();
638      }
639  
640      /**
# Line 619 | Line 646 | public abstract class ForkJoinTask<V> im
646       * @return the computed result
647       */
648      public final V invoke() {
649 <        if (doInvoke() != NORMAL)
650 <            return reportResult();
651 <        else
652 <            return getRawResult();
649 >        int s;
650 >        if ((s = doInvoke() & DONE_MASK) != NORMAL)
651 >            reportException(s);
652 >        return getRawResult();
653      }
654  
655      /**
# Line 649 | Line 676 | public abstract class ForkJoinTask<V> im
676       * @throws NullPointerException if any task is null
677       */
678      public static void invokeAll(ForkJoinTask<?> t1, ForkJoinTask<?> t2) {
679 +        int s1, s2;
680          t2.fork();
681 <        t1.invoke();
682 <        t2.join();
681 >        if ((s1 = t1.doInvoke() & DONE_MASK) != NORMAL)
682 >            t1.reportException(s1);
683 >        if ((s2 = t2.doJoin() & DONE_MASK) != NORMAL)
684 >            t2.reportException(s2);
685      }
686  
687      /**
# Line 694 | Line 724 | public abstract class ForkJoinTask<V> im
724              if (t != null) {
725                  if (ex != null)
726                      t.cancel(false);
727 <                else if (t.doJoin() < NORMAL && ex == null)
727 >                else if (t.doJoin() < NORMAL)
728                      ex = t.getException();
729              }
730          }
731          if (ex != null)
732 <            UNSAFE.throwException(ex);
732 >            U.throwException(ex);
733      }
734  
735      /**
# Line 751 | Line 781 | public abstract class ForkJoinTask<V> im
781              if (t != null) {
782                  if (ex != null)
783                      t.cancel(false);
784 <                else if (t.doJoin() < NORMAL && ex == null)
784 >                else if (t.doJoin() < NORMAL)
785                      ex = t.getException();
786              }
787          }
788          if (ex != null)
789 <            UNSAFE.throwException(ex);
789 >            U.throwException(ex);
790          return tasks;
791      }
792  
# Line 788 | Line 818 | public abstract class ForkJoinTask<V> im
818       * @return {@code true} if this task is now cancelled
819       */
820      public boolean cancel(boolean mayInterruptIfRunning) {
821 <        return setCompletion(CANCELLED) == CANCELLED;
792 <    }
793 <
794 <    /**
795 <     * Cancels, ignoring any exceptions thrown by cancel. Used during
796 <     * worker and pool shutdown. Cancel is spec'ed not to throw any
797 <     * exceptions, but if it does anyway, we have no recourse during
798 <     * shutdown, so guard against this case.
799 <     */
800 <    final void cancelIgnoringExceptions() {
801 <        try {
802 <            cancel(false);
803 <        } catch (Throwable ignore) {
804 <        }
821 >        return (setCompletion(CANCELLED) & DONE_MASK) == CANCELLED;
822      }
823  
824      public final boolean isDone() {
# Line 809 | Line 826 | public abstract class ForkJoinTask<V> im
826      }
827  
828      public final boolean isCancelled() {
829 <        return status == CANCELLED;
829 >        return (status & DONE_MASK) == CANCELLED;
830      }
831  
832      /**
# Line 829 | Line 846 | public abstract class ForkJoinTask<V> im
846       * exception and was not cancelled
847       */
848      public final boolean isCompletedNormally() {
849 <        return status == NORMAL;
849 >        return (status & DONE_MASK) == NORMAL;
850      }
851  
852      /**
# Line 840 | Line 857 | public abstract class ForkJoinTask<V> im
857       * @return the exception, or {@code null} if none
858       */
859      public final Throwable getException() {
860 <        int s = status;
860 >        int s = status & DONE_MASK;
861          return ((s >= NORMAL)    ? null :
862                  (s == CANCELLED) ? new CancellationException() :
863                  getThrowableException());
# Line 902 | Line 919 | public abstract class ForkJoinTask<V> im
919       */
920      public final V get() throws InterruptedException, ExecutionException {
921          int s = (Thread.currentThread() instanceof ForkJoinWorkerThread) ?
922 <            doJoin() : externalInterruptibleAwaitDone(0L);
922 >            doJoin() : externalInterruptibleAwaitDone();
923          Throwable ex;
924 <        if (s == CANCELLED)
924 >        if ((s &= DONE_MASK) == CANCELLED)
925              throw new CancellationException();
926          if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
927              throw new ExecutionException(ex);
# Line 927 | Line 944 | public abstract class ForkJoinTask<V> im
944       */
945      public final V get(long timeout, TimeUnit unit)
946          throws InterruptedException, ExecutionException, TimeoutException {
947 <        Thread t = Thread.currentThread();
948 <        if (t instanceof ForkJoinWorkerThread) {
949 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
950 <            long nanos = unit.toNanos(timeout);
951 <            if (status >= 0) {
952 <                boolean completed = false;
953 <                if (w.unpushTask(this)) {
954 <                    try {
955 <                        completed = exec();
956 <                    } catch (Throwable rex) {
957 <                        setExceptionalCompletion(rex);
947 >        if (Thread.interrupted())
948 >            throw new InterruptedException();
949 >        // Messy in part because we measure in nanosecs, but wait in millisecs
950 >        int s; long ns, ms;
951 >        if ((s = status) >= 0 && (ns = unit.toNanos(timeout)) > 0L) {
952 >            long deadline = System.nanoTime() + ns;
953 >            ForkJoinPool p = null;
954 >            ForkJoinPool.WorkQueue w = null;
955 >            Thread t = Thread.currentThread();
956 >            if (t instanceof ForkJoinWorkerThread) {
957 >                ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
958 >                p = wt.pool;
959 >                w = wt.workQueue;
960 >                s = p.helpJoinOnce(w, this); // no retries on failure
961 >            }
962 >            boolean canBlock = false;
963 >            boolean interrupted = false;
964 >            try {
965 >                while ((s = status) >= 0) {
966 >                    if (w != null && w.runState < 0)
967 >                        cancelIgnoringExceptions(this);
968 >                    else if (!canBlock) {
969 >                        if (p == null || p.tryCompensate(this, null))
970 >                            canBlock = true;
971 >                    }
972 >                    else {
973 >                        if ((ms = TimeUnit.NANOSECONDS.toMillis(ns)) > 0L &&
974 >                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
975 >                            synchronized (this) {
976 >                                if (status >= 0) {
977 >                                    try {
978 >                                        wait(ms);
979 >                                    } catch (InterruptedException ie) {
980 >                                        if (p == null)
981 >                                            interrupted = true;
982 >                                    }
983 >                                }
984 >                                else
985 >                                    notifyAll();
986 >                            }
987 >                        }
988 >                        if ((s = status) < 0 || interrupted ||
989 >                            (ns = deadline - System.nanoTime()) <= 0L)
990 >                            break;
991                      }
992                  }
993 <                if (completed)
994 <                    setCompletion(NORMAL);
995 <                else if (status >= 0 && nanos > 0)
946 <                    w.pool.timedAwaitJoin(this, nanos);
993 >            } finally {
994 >                if (p != null && canBlock)
995 >                    p.incrementActiveCount();
996              }
997 +            if (interrupted)
998 +                throw new InterruptedException();
999          }
1000 <        else {
950 <            long millis = unit.toMillis(timeout);
951 <            if (millis > 0)
952 <                externalInterruptibleAwaitDone(millis);
953 <        }
954 <        int s = status;
955 <        if (s != NORMAL) {
1000 >        if ((s &= DONE_MASK) != NORMAL) {
1001              Throwable ex;
1002              if (s == CANCELLED)
1003                  throw new CancellationException();
# Line 997 | Line 1042 | public abstract class ForkJoinTask<V> im
1042       * ClassCastException}.
1043       */
1044      public static void helpQuiesce() {
1045 <        ((ForkJoinWorkerThread) Thread.currentThread())
1046 <            .helpQuiescePool();
1045 >        ForkJoinWorkerThread wt =
1046 >            (ForkJoinWorkerThread)Thread.currentThread();
1047 >        wt.pool.helpQuiescePool(wt.workQueue);
1048      }
1049  
1050      /**
# Line 1018 | Line 1064 | public abstract class ForkJoinTask<V> im
1064       * setRawResult(null)}.
1065       */
1066      public void reinitialize() {
1067 <        if (status == EXCEPTIONAL)
1067 >        if ((status & DONE_MASK) == EXCEPTIONAL)
1068              clearExceptionalCompletion();
1069          else
1070              status = 0;
# Line 1066 | Line 1112 | public abstract class ForkJoinTask<V> im
1112       * @return {@code true} if unforked
1113       */
1114      public boolean tryUnfork() {
1115 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1116 <            .unpushTask(this);
1115 >        return ((ForkJoinWorkerThread)Thread.currentThread())
1116 >            .workQueue.tryUnpush(this);
1117      }
1118  
1119      /**
# Line 1086 | Line 1132 | public abstract class ForkJoinTask<V> im
1132       */
1133      public static int getQueuedTaskCount() {
1134          return ((ForkJoinWorkerThread) Thread.currentThread())
1135 <            .getQueueSize();
1135 >            .workQueue.queueSize();
1136      }
1137  
1138      /**
# Line 1108 | Line 1154 | public abstract class ForkJoinTask<V> im
1154       * @return the surplus number of tasks, which may be negative
1155       */
1156      public static int getSurplusQueuedTaskCount() {
1157 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1158 <            .getEstimatedSurplusTaskCount();
1157 >        /*
1158 >         * The aim of this method is to return a cheap heuristic guide
1159 >         * for task partitioning when programmers, frameworks, tools,
1160 >         * or languages have little or no idea about task granularity.
1161 >         * In essence by offering this method, we ask users only about
1162 >         * tradeoffs in overhead vs expected throughput and its
1163 >         * variance, rather than how finely to partition tasks.
1164 >         *
1165 >         * In a steady state strict (tree-structured) computation,
1166 >         * each thread makes available for stealing enough tasks for
1167 >         * other threads to remain active. Inductively, if all threads
1168 >         * play by the same rules, each thread should make available
1169 >         * only a constant number of tasks.
1170 >         *
1171 >         * The minimum useful constant is just 1. But using a value of
1172 >         * 1 would require immediate replenishment upon each steal to
1173 >         * maintain enough tasks, which is infeasible.  Further,
1174 >         * partitionings/granularities of offered tasks should
1175 >         * minimize steal rates, which in general means that threads
1176 >         * nearer the top of computation tree should generate more
1177 >         * than those nearer the bottom. In perfect steady state, each
1178 >         * thread is at approximately the same level of computation
1179 >         * tree. However, producing extra tasks amortizes the
1180 >         * uncertainty of progress and diffusion assumptions.
1181 >         *
1182 >         * So, users will want to use values larger, but not much
1183 >         * larger than 1 to both smooth over transient shortages and
1184 >         * hedge against uneven progress; as traded off against the
1185 >         * cost of extra task overhead. We leave the user to pick a
1186 >         * threshold value to compare with the results of this call to
1187 >         * guide decisions, but recommend values such as 3.
1188 >         *
1189 >         * When all threads are active, it is on average OK to
1190 >         * estimate surplus strictly locally. In steady-state, if one
1191 >         * thread is maintaining say 2 surplus tasks, then so are
1192 >         * others. So we can just use estimated queue length.
1193 >         * However, this strategy alone leads to serious mis-estimates
1194 >         * in some non-steady-state conditions (ramp-up, ramp-down,
1195 >         * other stalls). We can detect many of these by further
1196 >         * considering the number of "idle" threads, that are known to
1197 >         * have zero queued tasks, so compensate by a factor of
1198 >         * (#idle/#active) threads.
1199 >         */
1200 >        ForkJoinWorkerThread wt =
1201 >            (ForkJoinWorkerThread)Thread.currentThread();
1202 >        return wt.workQueue.queueSize() - wt.pool.idlePerActive();
1203      }
1204  
1205      // Extension methods
# Line 1166 | Line 1256 | public abstract class ForkJoinTask<V> im
1256       * @return the next task, or {@code null} if none are available
1257       */
1258      protected static ForkJoinTask<?> peekNextLocalTask() {
1259 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1170 <            .peekTask();
1259 >        return ((ForkJoinWorkerThread) Thread.currentThread()).workQueue.peek();
1260      }
1261  
1262      /**
# Line 1186 | Line 1275 | public abstract class ForkJoinTask<V> im
1275       */
1276      protected static ForkJoinTask<?> pollNextLocalTask() {
1277          return ((ForkJoinWorkerThread) Thread.currentThread())
1278 <            .pollLocalTask();
1278 >            .workQueue.nextLocalTask();
1279      }
1280  
1281      /**
# Line 1208 | Line 1297 | public abstract class ForkJoinTask<V> im
1297       * @return a task, or {@code null} if none are available
1298       */
1299      protected static ForkJoinTask<?> pollTask() {
1300 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1301 <            .pollTask();
1300 >        ForkJoinWorkerThread wt =
1301 >            (ForkJoinWorkerThread)Thread.currentThread();
1302 >        return wt.pool.nextTaskFor(wt.workQueue);
1303 >    }
1304 >
1305 >    // Mark-bit operations
1306 >
1307 >    /**
1308 >     * Returns true if this task is marked.
1309 >     *
1310 >     * @return true if this task is marked
1311 >     * @since 1.8
1312 >     */
1313 >    public final boolean isMarkedForkJoinTask() {
1314 >        return (status & MARKED) != 0;
1315 >    }
1316 >
1317 >    /**
1318 >     * Atomically sets the mark on this task.
1319 >     *
1320 >     * @return true if this task was previously unmarked
1321 >     * @since 1.8
1322 >     */
1323 >    public final boolean markForkJoinTask() {
1324 >        for (int s;;) {
1325 >            if (((s = status) & MARKED) != 0)
1326 >                return false;
1327 >            if (U.compareAndSwapInt(this, STATUS, s, s | MARKED))
1328 >                return true;
1329 >        }
1330 >    }
1331 >
1332 >    /**
1333 >     * Atomically clears the mark on this task.
1334 >     *
1335 >     * @return true if this task was previously marked
1336 >     * @since 1.8
1337 >     */
1338 >    public final boolean unmarkForkJoinTask() {
1339 >        for (int s;;) {
1340 >            if (((s = status) & MARKED) == 0)
1341 >                return false;
1342 >            if (U.compareAndSwapInt(this, STATUS, s, s & ~MARKED))
1343 >                return true;
1344 >        }
1345      }
1346  
1347      /**
# Line 1220 | Line 1352 | public abstract class ForkJoinTask<V> im
1352      static final class AdaptedRunnable<T> extends ForkJoinTask<T>
1353          implements RunnableFuture<T> {
1354          final Runnable runnable;
1223        final T resultOnCompletion;
1355          T result;
1356          AdaptedRunnable(Runnable runnable, T result) {
1357              if (runnable == null) throw new NullPointerException();
1358              this.runnable = runnable;
1359 <            this.resultOnCompletion = result;
1359 >            this.result = result; // OK to set this even before completion
1360          }
1361 <        public T getRawResult() { return result; }
1362 <        public void setRawResult(T v) { result = v; }
1363 <        public boolean exec() {
1364 <            runnable.run();
1365 <            result = resultOnCompletion;
1366 <            return true;
1361 >        public final T getRawResult() { return result; }
1362 >        public final void setRawResult(T v) { result = v; }
1363 >        public final boolean exec() { runnable.run(); return true; }
1364 >        public final void run() { invoke(); }
1365 >        private static final long serialVersionUID = 5232453952276885070L;
1366 >    }
1367 >
1368 >    /**
1369 >     * Adaptor for Runnables without results
1370 >     */
1371 >    static final class AdaptedRunnableAction extends ForkJoinTask<Void>
1372 >        implements RunnableFuture<Void> {
1373 >        final Runnable runnable;
1374 >        AdaptedRunnableAction(Runnable runnable) {
1375 >            if (runnable == null) throw new NullPointerException();
1376 >            this.runnable = runnable;
1377          }
1378 <        public void run() { invoke(); }
1378 >        public final Void getRawResult() { return null; }
1379 >        public final void setRawResult(Void v) { }
1380 >        public final boolean exec() { runnable.run(); return true; }
1381 >        public final void run() { invoke(); }
1382          private static final long serialVersionUID = 5232453952276885070L;
1383      }
1384  
# Line 1249 | Line 1393 | public abstract class ForkJoinTask<V> im
1393              if (callable == null) throw new NullPointerException();
1394              this.callable = callable;
1395          }
1396 <        public T getRawResult() { return result; }
1397 <        public void setRawResult(T v) { result = v; }
1398 <        public boolean exec() {
1396 >        public final T getRawResult() { return result; }
1397 >        public final void setRawResult(T v) { result = v; }
1398 >        public final boolean exec() {
1399              try {
1400                  result = callable.call();
1401                  return true;
# Line 1263 | Line 1407 | public abstract class ForkJoinTask<V> im
1407                  throw new RuntimeException(ex);
1408              }
1409          }
1410 <        public void run() { invoke(); }
1410 >        public final void run() { invoke(); }
1411          private static final long serialVersionUID = 2838392045355241008L;
1412      }
1413  
# Line 1276 | Line 1420 | public abstract class ForkJoinTask<V> im
1420       * @return the task
1421       */
1422      public static ForkJoinTask<?> adapt(Runnable runnable) {
1423 <        return new AdaptedRunnable<Void>(runnable, null);
1423 >        return new AdaptedRunnableAction(runnable);
1424      }
1425  
1426      /**
# Line 1310 | Line 1454 | public abstract class ForkJoinTask<V> im
1454      private static final long serialVersionUID = -7721805057305804111L;
1455  
1456      /**
1457 <     * Saves the state to a stream (that is, serializes it).
1457 >     * Saves this task to a stream (that is, serializes it).
1458       *
1459       * @serialData the current run status and the exception thrown
1460       * during execution, or {@code null} if none
1317     * @param s the stream
1461       */
1462      private void writeObject(java.io.ObjectOutputStream s)
1463          throws java.io.IOException {
# Line 1323 | Line 1466 | public abstract class ForkJoinTask<V> im
1466      }
1467  
1468      /**
1469 <     * Reconstitutes the instance from a stream (that is, deserializes it).
1327 <     *
1328 <     * @param s the stream
1469 >     * Reconstitutes this task from a stream (that is, deserializes it).
1470       */
1471      private void readObject(java.io.ObjectInputStream s)
1472          throws java.io.IOException, ClassNotFoundException {
# Line 1336 | Line 1477 | public abstract class ForkJoinTask<V> im
1477      }
1478  
1479      // Unsafe mechanics
1480 <    private static final sun.misc.Unsafe UNSAFE;
1481 <    private static final long statusOffset;
1480 >    private static final sun.misc.Unsafe U;
1481 >    private static final long STATUS;
1482      static {
1483          exceptionTableLock = new ReentrantLock();
1484          exceptionTableRefQueue = new ReferenceQueue<Object>();
1485          exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1486          try {
1487 <            UNSAFE = getUnsafe();
1488 <            statusOffset = UNSAFE.objectFieldOffset
1487 >            U = getUnsafe();
1488 >            STATUS = U.objectFieldOffset
1489                  (ForkJoinTask.class.getDeclaredField("status"));
1490          } catch (Exception e) {
1491              throw new Error(e);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines