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.81 by dl, Thu Jan 26 00:08:13 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 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
147 > * processed. Also, completion based designs can use them to record
148 > * that one subtask has completed. (Method names for marking are bulky
149 > * in part 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 number of times to try to help join a task without any
202 >     * apparent progress before giving up and blocking. The value is
203 >     * arbitrary but should be large enough to cope with transient
204 >     * stalls (due to GC etc) that can cause helping methods not to be
205 >     * able to proceed because other workers have not progressed to
206 >     * the point where subtasks can be found or taken.
207       */
208 +    private static final int HELP_RETRIES = 32;
209  
210      /*
211       * The status field holds run control status bits packed into a
# Line 192 | Line 226 | public abstract class ForkJoinTask<V> im
226  
227      /** The run status of this task */
228      volatile int status; // accessed directly by pool and workers
229 <    private static final int NORMAL      = -1;
230 <    private static final int CANCELLED   = -2;
231 <    private static final int EXCEPTIONAL = -3;
232 <    private static final int SIGNAL      =  1;
229 >    static final int NORMAL      = 0xfffffffc;  // negative with low 2 bits 0
230 >    static final int CANCELLED   = 0xfffffff8;  // must be < NORMAL
231 >    static final int EXCEPTIONAL = 0xfffffff4;  // must be < CANCELLED
232 >    static final int SIGNAL      = 0x00000001;
233 >    static final int MARKED      = 0x00000002;
234  
235      /**
236 <     * Marks completion and wakes up threads waiting to join this task,
237 <     * also clearing signal request bits.
236 >     * Marks completion and wakes up threads waiting to join this
237 >     * task, also clearing signal request bits. A specialization for
238 >     * NORMAL completion is in method doExec
239       *
240       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
241       * @return completion status on exit
# Line 208 | Line 244 | public abstract class ForkJoinTask<V> im
244          for (int s;;) {
245              if ((s = status) < 0)
246                  return s;
247 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
248 <                if (s != 0)
247 >            if (U.compareAndSwapInt(this, STATUS, s, (s & ~SIGNAL)|completion)) {
248 >                if ((s & SIGNAL) != 0)
249                      synchronized (this) { notifyAll(); }
250                  return completion;
251              }
# Line 217 | Line 253 | public abstract class ForkJoinTask<V> im
253      }
254  
255      /**
256 <     * Tries to block a worker thread until completed or timed out.
257 <     * Uses Object.wait time argument conventions.
258 <     * May fail on contention or interrupt.
256 >     * Primary execution method for stolen tasks. Unless done, calls
257 >     * exec and records status if completed, but doesn't wait for
258 >     * completion otherwise.
259       *
260 <     * @param millis if > 0, wait time.
260 >     * @return status on exit from this method
261       */
262 <    final void tryAwaitDone(long millis) {
263 <        int s;
264 <        try {
265 <            if (((s = status) > 0 ||
266 <                 (s == 0 &&
267 <                  UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
268 <                status > 0) {
269 <                synchronized (this) {
270 <                    if (status > 0)
271 <                        wait(millis);
262 >    final int doExec() {
263 >        int s; boolean completed;
264 >        if ((s = status) >= 0) {
265 >            try {
266 >                completed = exec();
267 >            } catch (Throwable rex) {
268 >                return setExceptionalCompletion(rex);
269 >            }
270 >            while ((s = status) >= 0 && completed) {
271 >                if (U.compareAndSwapInt(this, STATUS, s, (s & ~SIGNAL)|NORMAL)) {
272 >                    if ((s & SIGNAL) != 0)
273 >                        synchronized (this) { notifyAll(); }
274 >                    return NORMAL;
275                  }
276              }
238        } catch (InterruptedException ie) {
239            // caller must check termination
277          }
278 +        return s;
279      }
280  
281      /**
# Line 250 | Line 288 | public abstract class ForkJoinTask<V> im
288              boolean interrupted = false;
289              synchronized (this) {
290                  while ((s = status) >= 0) {
291 <                    if (s == 0)
254 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
255 <                                                 0, SIGNAL);
256 <                    else {
291 >                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
292                          try {
293                              wait();
294                          } catch (InterruptedException ie) {
# Line 279 | Line 314 | public abstract class ForkJoinTask<V> im
314          if ((s = status) >= 0) {
315              synchronized (this) {
316                  while ((s = status) >= 0) {
317 <                    if (s == 0)
283 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
284 <                                                 0, SIGNAL);
285 <                    else
317 >                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
318                          wait(millis);
319 +                        if (millis > 0L)
320 +                            break;
321 +                    }
322                  }
323              }
324          }
325          return s;
326      }
327  
328 +
329      /**
330 <     * Primary execution method for stolen tasks. Unless done, calls
331 <     * exec and records status if completed, but doesn't wait for
332 <     * completion otherwise.
330 >     * Implementation for join, get, quietlyJoin. Directly handles
331 >     * only cases of already-completed, external wait, and
332 >     * unfork+exec.  Others are relayed to awaitJoin.
333 >     *
334 >     * @return status upon completion
335       */
336 <    final void doExec() {
337 <        if (status >= 0) {
338 <            boolean completed;
339 <            try {
340 <                completed = exec();
341 <            } catch (Throwable rex) {
342 <                setExceptionalCompletion(rex);
343 <                return;
306 <            }
307 <            if (completed)
308 <                setCompletion(NORMAL); // must be outside try block
336 >    private int doJoin() {
337 >        int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
338 >        if ((s = status) >= 0) {
339 >            if (!((t = Thread.currentThread()) instanceof ForkJoinWorkerThread))
340 >                s = externalAwaitDone();
341 >            else if (!(w = (wt = (ForkJoinWorkerThread)t).workQueue).
342 >                     tryUnpush(this) || (s = doExec()) >= 0)
343 >                s = awaitJoin(w, wt.pool);
344          }
345 +        return s;
346      }
347  
348      /**
349 <     * Primary mechanics for join, get, quietlyJoin.
349 >     * Helps and/or blocks until joined.
350 >     *
351 >     * @param w the joiner
352 >     * @param p the pool
353       * @return status upon completion
354       */
355 <    private int doJoin() {
356 <        Thread t; ForkJoinWorkerThread w; int s; boolean completed;
357 <        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
358 <            if ((s = status) < 0)
359 <                return s;
360 <            if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
355 >    private int awaitJoin(ForkJoinPool.WorkQueue w, ForkJoinPool p) {
356 >        int s;
357 >        ForkJoinTask<?> prevJoin = w.currentJoin;
358 >        w.currentJoin = this;
359 >        for (int k = HELP_RETRIES; (s = status) >= 0;) {
360 >            if ((w.queueSize() > 0) ?
361 >                w.tryRemoveAndExec(this) :        // self-help
362 >                p.tryHelpStealer(w, this))        // help process tasks
363 >                k = HELP_RETRIES;                 // reset if made progress
364 >            else if ((s = status) < 0)            // recheck
365 >                break;
366 >            else if (--k > 0) {
367 >                if ((k & 3) == 1)
368 >                    Thread.yield();               // occasionally yield
369 >            }
370 >            else if (k == 0)
371 >                p.tryPollForAndExec(w, this);     // uncommon self-help case
372 >            else if (p.tryCompensate()) {         // true if can block
373                  try {
374 <                    completed = exec();
375 <                } catch (Throwable rex) {
376 <                    return setExceptionalCompletion(rex);
374 >                    int ss = status;
375 >                    if (ss >= 0 &&                // assert need signal
376 >                        U.compareAndSwapInt(this, STATUS, ss, ss | SIGNAL)) {
377 >                        synchronized (this) {
378 >                            if (status >= 0)      // block
379 >                                wait();
380 >                        }
381 >                    }
382 >                } catch (InterruptedException ignore) {
383 >                } finally {
384 >                    p.incrementActiveCount();     // re-activate
385                  }
327                if (completed)
328                    return setCompletion(NORMAL);
386              }
330            return w.joinTask(this);
387          }
388 <        else
389 <            return externalAwaitDone();
388 >        w.currentJoin = prevJoin;
389 >        return s;
390      }
391  
392      /**
393 <     * Primary mechanics for invoke, quietlyInvoke.
393 >     * Implementation for invoke, quietlyInvoke.
394 >     *
395       * @return status upon completion
396       */
397      private int doInvoke() {
398 <        int s; boolean completed;
399 <        if ((s = status) < 0)
398 >        int s;
399 >        if ((s = doExec()) < 0)
400              return s;
344        try {
345            completed = exec();
346        } catch (Throwable rex) {
347            return setExceptionalCompletion(rex);
348        }
349        if (completed)
350            return setCompletion(NORMAL);
401          else
402              return doJoin();
403      }
# Line 381 | Line 431 | public abstract class ForkJoinTask<V> im
431       * periods. However, since we do not know when the last joiner
432       * completes, we must use weak references and expunge them. We do
433       * so on each operation (hence full locking). Also, some thread in
434 <     * any ForkJoinPool will call helpExpunge when its pool becomes
435 <     * isQuiescent.
434 >     * any ForkJoinPool will call helpExpungeStaleExceptions when its
435 >     * pool becomes isQuiescent.
436       */
437      static final class ExceptionNode extends WeakReference<ForkJoinTask<?>>{
438          final Throwable ex;
439          ExceptionNode next;
440 <        final long thrower;
440 >        final long thrower;  // use id not ref to avoid weak cycles
441          ExceptionNode(ForkJoinTask<?> task, Throwable ex, ExceptionNode next) {
442              super(task, exceptionTableRefQueue);
443              this.ex = ex;
# Line 403 | Line 453 | public abstract class ForkJoinTask<V> im
453       */
454      private int setExceptionalCompletion(Throwable ex) {
455          int h = System.identityHashCode(this);
456 <        ReentrantLock lock = exceptionTableLock;
456 >        final ReentrantLock lock = exceptionTableLock;
457          lock.lock();
458          try {
459              expungeStaleExceptions();
# Line 424 | Line 474 | public abstract class ForkJoinTask<V> im
474      }
475  
476      /**
477 +     * Cancels, ignoring any exceptions thrown by cancel. Used during
478 +     * worker and pool shutdown. Cancel is spec'ed not to throw any
479 +     * exceptions, but if it does anyway, we have no recourse during
480 +     * shutdown, so guard against this case.
481 +     */
482 +    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
483 +        if (t != null && t.status >= 0) {
484 +            try {
485 +                t.cancel(false);
486 +            } catch (Throwable ignore) {
487 +            }
488 +        }
489 +    }
490 +
491 +    /**
492       * Removes exception node and clears status
493       */
494      private void clearExceptionalCompletion() {
495          int h = System.identityHashCode(this);
496 <        ReentrantLock lock = exceptionTableLock;
496 >        final ReentrantLock lock = exceptionTableLock;
497          lock.lock();
498          try {
499              ExceptionNode[] t = exceptionTable;
# Line 473 | Line 538 | public abstract class ForkJoinTask<V> im
538              return null;
539          int h = System.identityHashCode(this);
540          ExceptionNode e;
541 <        ReentrantLock lock = exceptionTableLock;
541 >        final ReentrantLock lock = exceptionTableLock;
542          lock.lock();
543          try {
544              expungeStaleExceptions();
# Line 488 | Line 553 | public abstract class ForkJoinTask<V> im
553          if (e == null || (ex = e.ex) == null)
554              return null;
555          if (e.thrower != Thread.currentThread().getId()) {
556 <            Class ec = ex.getClass();
556 >            Class<? extends Throwable> ec = ex.getClass();
557              try {
558                  Constructor<?> noArgCtor = null;
559                  Constructor<?>[] cs = ec.getConstructors();// public ctors only
# Line 539 | Line 604 | public abstract class ForkJoinTask<V> im
604      }
605  
606      /**
607 <     * If lock is available, poll any stale refs and remove them.
607 >     * If lock is available, poll stale refs and remove them.
608       * Called from ForkJoinPool when pools become quiescent.
609       */
610      static final void helpExpungeStaleExceptions() {
611 <        ReentrantLock lock = exceptionTableLock;
611 >        final ReentrantLock lock = exceptionTableLock;
612          if (lock.tryLock()) {
613              try {
614                  expungeStaleExceptions();
# Line 562 | Line 627 | public abstract class ForkJoinTask<V> im
627          if ((s = status) == CANCELLED)
628              throw new CancellationException();
629          if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
630 <            UNSAFE.throwException(ex);
630 >            U.throwException(ex);
631          return getRawResult();
632      }
633  
# Line 587 | Line 652 | public abstract class ForkJoinTask<V> im
652       * @return {@code this}, to simplify usage
653       */
654      public final ForkJoinTask<V> fork() {
655 <        ((ForkJoinWorkerThread) Thread.currentThread())
656 <            .pushTask(this);
655 >        ForkJoinWorkerThread wt;
656 >        (wt = (ForkJoinWorkerThread)Thread.currentThread()).
657 >            workQueue.push(this, wt.pool);
658          return this;
659      }
660  
# Line 694 | Line 760 | public abstract class ForkJoinTask<V> im
760              if (t != null) {
761                  if (ex != null)
762                      t.cancel(false);
763 <                else if (t.doJoin() < NORMAL && ex == null)
763 >                else if (t.doJoin() < NORMAL)
764                      ex = t.getException();
765              }
766          }
767          if (ex != null)
768 <            UNSAFE.throwException(ex);
768 >            U.throwException(ex);
769      }
770  
771      /**
# Line 751 | Line 817 | public abstract class ForkJoinTask<V> im
817              if (t != null) {
818                  if (ex != null)
819                      t.cancel(false);
820 <                else if (t.doJoin() < NORMAL && ex == null)
820 >                else if (t.doJoin() < NORMAL)
821                      ex = t.getException();
822              }
823          }
824          if (ex != null)
825 <            UNSAFE.throwException(ex);
825 >            U.throwException(ex);
826          return tasks;
827      }
828  
# Line 791 | Line 857 | public abstract class ForkJoinTask<V> im
857          return setCompletion(CANCELLED) == CANCELLED;
858      }
859  
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        }
805    }
806
860      public final boolean isDone() {
861          return status < 0;
862      }
# Line 927 | Line 980 | public abstract class ForkJoinTask<V> im
980       */
981      public final V get(long timeout, TimeUnit unit)
982          throws InterruptedException, ExecutionException, TimeoutException {
983 +        // Messy in part because we measure in nanos, but wait in millis
984 +        int s; long millis, nanos;
985          Thread t = Thread.currentThread();
986 <        if (t instanceof ForkJoinWorkerThread) {
987 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
988 <            long nanos = unit.toNanos(timeout);
989 <            if (status >= 0) {
990 <                boolean completed = false;
991 <                if (w.unpushTask(this)) {
992 <                    try {
993 <                        completed = exec();
994 <                    } catch (Throwable rex) {
995 <                        setExceptionalCompletion(rex);
986 >        if (!(t instanceof ForkJoinWorkerThread)) {
987 >            if ((millis = unit.toMillis(timeout)) > 0L)
988 >                s = externalInterruptibleAwaitDone(millis);
989 >            else
990 >                s = status;
991 >        }
992 >        else if ((s = status) >= 0 && (nanos = unit.toNanos(timeout)) > 0L) {
993 >            long deadline = System.nanoTime() + nanos;
994 >            ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
995 >            ForkJoinPool.WorkQueue w = wt.workQueue;
996 >            ForkJoinPool p = wt.pool;
997 >            if (w.tryUnpush(this))
998 >                doExec();
999 >            boolean blocking = false;
1000 >            try {
1001 >                while ((s = status) >= 0) {
1002 >                    if (w.runState < 0)
1003 >                        cancelIgnoringExceptions(this);
1004 >                    else if (!blocking)
1005 >                        blocking = p.tryCompensate();
1006 >                    else {
1007 >                        millis = TimeUnit.NANOSECONDS.toMillis(nanos);
1008 >                        if (millis > 0L &&
1009 >                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
1010 >                            try {
1011 >                                synchronized (this) {
1012 >                                    if (status >= 0)
1013 >                                        wait(millis);
1014 >                                }
1015 >                            } catch (InterruptedException ie) {
1016 >                            }
1017 >                        }
1018 >                        if ((s = status) < 0 ||
1019 >                            (nanos = deadline - System.nanoTime()) <= 0L)
1020 >                            break;
1021                      }
1022                  }
1023 <                if (completed)
1024 <                    setCompletion(NORMAL);
1025 <                else if (status >= 0 && nanos > 0)
946 <                    w.pool.timedAwaitJoin(this, nanos);
1023 >            } finally {
1024 >                if (blocking)
1025 >                    p.incrementActiveCount();
1026              }
1027          }
949        else {
950            long millis = unit.toMillis(timeout);
951            if (millis > 0)
952                externalInterruptibleAwaitDone(millis);
953        }
954        int s = status;
1028          if (s != NORMAL) {
1029              Throwable ex;
1030              if (s == CANCELLED)
# Line 997 | Line 1070 | public abstract class ForkJoinTask<V> im
1070       * ClassCastException}.
1071       */
1072      public static void helpQuiesce() {
1073 <        ((ForkJoinWorkerThread) Thread.currentThread())
1074 <            .helpQuiescePool();
1073 >        ForkJoinWorkerThread w =
1074 >            (ForkJoinWorkerThread)Thread.currentThread();
1075 >        w.pool.helpQuiescePool(w.workQueue);
1076      }
1077  
1078      /**
# Line 1066 | Line 1140 | public abstract class ForkJoinTask<V> im
1140       * @return {@code true} if unforked
1141       */
1142      public boolean tryUnfork() {
1143 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1144 <            .unpushTask(this);
1143 >        return ((ForkJoinWorkerThread)Thread.currentThread())
1144 >            .workQueue.tryUnpush(this);
1145      }
1146  
1147      /**
# Line 1086 | Line 1160 | public abstract class ForkJoinTask<V> im
1160       */
1161      public static int getQueuedTaskCount() {
1162          return ((ForkJoinWorkerThread) Thread.currentThread())
1163 <            .getQueueSize();
1163 >            .workQueue.queueSize();
1164      }
1165  
1166      /**
# Line 1108 | Line 1182 | public abstract class ForkJoinTask<V> im
1182       * @return the surplus number of tasks, which may be negative
1183       */
1184      public static int getSurplusQueuedTaskCount() {
1185 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1186 <            .getEstimatedSurplusTaskCount();
1185 >        /*
1186 >         * The aim of this method is to return a cheap heuristic guide
1187 >         * for task partitioning when programmers, frameworks, tools,
1188 >         * or languages have little or no idea about task granularity.
1189 >         * In essence by offering this method, we ask users only about
1190 >         * tradeoffs in overhead vs expected throughput and its
1191 >         * variance, rather than how finely to partition tasks.
1192 >         *
1193 >         * In a steady state strict (tree-structured) computation,
1194 >         * each thread makes available for stealing enough tasks for
1195 >         * other threads to remain active. Inductively, if all threads
1196 >         * play by the same rules, each thread should make available
1197 >         * only a constant number of tasks.
1198 >         *
1199 >         * The minimum useful constant is just 1. But using a value of
1200 >         * 1 would require immediate replenishment upon each steal to
1201 >         * maintain enough tasks, which is infeasible.  Further,
1202 >         * partitionings/granularities of offered tasks should
1203 >         * minimize steal rates, which in general means that threads
1204 >         * nearer the top of computation tree should generate more
1205 >         * than those nearer the bottom. In perfect steady state, each
1206 >         * thread is at approximately the same level of computation
1207 >         * tree. However, producing extra tasks amortizes the
1208 >         * uncertainty of progress and diffusion assumptions.
1209 >         *
1210 >         * So, users will want to use values larger, but not much
1211 >         * larger than 1 to both smooth over transient shortages and
1212 >         * hedge against uneven progress; as traded off against the
1213 >         * cost of extra task overhead. We leave the user to pick a
1214 >         * threshold value to compare with the results of this call to
1215 >         * guide decisions, but recommend values such as 3.
1216 >         *
1217 >         * When all threads are active, it is on average OK to
1218 >         * estimate surplus strictly locally. In steady-state, if one
1219 >         * thread is maintaining say 2 surplus tasks, then so are
1220 >         * others. So we can just use estimated queue length.
1221 >         * However, this strategy alone leads to serious mis-estimates
1222 >         * in some non-steady-state conditions (ramp-up, ramp-down,
1223 >         * other stalls). We can detect many of these by further
1224 >         * considering the number of "idle" threads, that are known to
1225 >         * have zero queued tasks, so compensate by a factor of
1226 >         * (#idle/#active) threads.
1227 >         */
1228 >        ForkJoinWorkerThread w =
1229 >            (ForkJoinWorkerThread)Thread.currentThread();
1230 >        return w.workQueue.queueSize() - w.pool.idlePerActive();
1231      }
1232  
1233      // Extension methods
# Line 1166 | Line 1284 | public abstract class ForkJoinTask<V> im
1284       * @return the next task, or {@code null} if none are available
1285       */
1286      protected static ForkJoinTask<?> peekNextLocalTask() {
1287 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1170 <            .peekTask();
1287 >        return ((ForkJoinWorkerThread) Thread.currentThread()).workQueue.peek();
1288      }
1289  
1290      /**
# Line 1186 | Line 1303 | public abstract class ForkJoinTask<V> im
1303       */
1304      protected static ForkJoinTask<?> pollNextLocalTask() {
1305          return ((ForkJoinWorkerThread) Thread.currentThread())
1306 <            .pollLocalTask();
1306 >            .workQueue.nextLocalTask();
1307      }
1308  
1309      /**
# Line 1208 | Line 1325 | public abstract class ForkJoinTask<V> im
1325       * @return a task, or {@code null} if none are available
1326       */
1327      protected static ForkJoinTask<?> pollTask() {
1328 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1329 <            .pollTask();
1328 >        ForkJoinWorkerThread w =
1329 >            (ForkJoinWorkerThread)Thread.currentThread();
1330 >        return w.pool.nextTaskFor(w.workQueue);
1331 >    }
1332 >
1333 >    // Mark-bit operations
1334 >
1335 >    /**
1336 >     * Returns true if this task is marked.
1337 >     *
1338 >     * @return true if this task is marked
1339 >     * @since 1.8
1340 >     */
1341 >    public final boolean isMarkedForkJoinTask() {
1342 >        return (status & MARKED) != 0;
1343 >    }
1344 >
1345 >    /**
1346 >     * Atomically sets the mark on this task.
1347 >     *
1348 >     * @return true if this task was previously unmarked
1349 >     * @since 1.8
1350 >     */
1351 >    public final boolean markForkJoinTask() {
1352 >        for (int s;;) {
1353 >            if (((s = status) & MARKED) != 0)
1354 >                return false;
1355 >            if (U.compareAndSwapInt(this, STATUS, s, s | MARKED))
1356 >                return true;
1357 >        }
1358 >    }
1359 >
1360 >    /**
1361 >     * Atomically clears the mark on this task.
1362 >     *
1363 >     * @return true if this task was previously marked
1364 >     * @since 1.8
1365 >     */
1366 >    public final boolean unmarkForkJoinTask() {
1367 >        for (int s;;) {
1368 >            if (((s = status) & MARKED) == 0)
1369 >                return false;
1370 >            if (U.compareAndSwapInt(this, STATUS, s, s & ~MARKED))
1371 >                return true;
1372 >        }
1373      }
1374  
1375      /**
# Line 1310 | Line 1470 | public abstract class ForkJoinTask<V> im
1470      private static final long serialVersionUID = -7721805057305804111L;
1471  
1472      /**
1473 <     * Saves the state to a stream (that is, serializes it).
1473 >     * Saves this task to a stream (that is, serializes it).
1474       *
1475       * @serialData the current run status and the exception thrown
1476       * during execution, or {@code null} if none
1317     * @param s the stream
1477       */
1478      private void writeObject(java.io.ObjectOutputStream s)
1479          throws java.io.IOException {
# Line 1323 | Line 1482 | public abstract class ForkJoinTask<V> im
1482      }
1483  
1484      /**
1485 <     * Reconstitutes the instance from a stream (that is, deserializes it).
1327 <     *
1328 <     * @param s the stream
1485 >     * Reconstitutes this task from a stream (that is, deserializes it).
1486       */
1487      private void readObject(java.io.ObjectInputStream s)
1488          throws java.io.IOException, ClassNotFoundException {
# Line 1336 | Line 1493 | public abstract class ForkJoinTask<V> im
1493      }
1494  
1495      // Unsafe mechanics
1496 <    private static final sun.misc.Unsafe UNSAFE;
1497 <    private static final long statusOffset;
1496 >    private static final sun.misc.Unsafe U;
1497 >    private static final long STATUS;
1498      static {
1499          exceptionTableLock = new ReentrantLock();
1500          exceptionTableRefQueue = new ReferenceQueue<Object>();
1501          exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1502          try {
1503 <            UNSAFE = getUnsafe();
1504 <            statusOffset = UNSAFE.objectFieldOffset
1503 >            U = getUnsafe();
1504 >            STATUS = U.objectFieldOffset
1505                  (ForkJoinTask.class.getDeclaredField("status"));
1506          } catch (Exception e) {
1507              throw new Error(e);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines