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

Comparing jsr166/src/main/java/util/concurrent/ForkJoinTask.java (file contents):
Revision 1.53 by jsr166, Mon Dec 12 20:53:11 2011 UTC vs.
Revision 1.54 by dl, Thu Jan 26 00:08:17 2012 UTC

# Line 43 | Line 43 | import java.lang.reflect.Constructor;
43   * <p>A {@code ForkJoinTask} is a lightweight form of {@link Future}.
44   * The efficiency of {@code ForkJoinTask}s stems from a set of
45   * restrictions (that are only partially statically enforceable)
46 < * reflecting their intended use as computational tasks calculating
47 < * pure functions or operating on purely isolated objects.  The
48 < * primary coordination mechanisms are {@link #fork}, that arranges
46 > * reflecting their main use as computational tasks calculating pure
47 > * functions or operating on purely isolated objects.  The primary
48 > * coordination mechanisms are {@link #fork}, that arranges
49   * asynchronous execution, and {@link #join}, that doesn't proceed
50   * until the task's result has been computed.  Computations should
51 < * avoid {@code synchronized} methods or blocks, and should minimize
52 < * other blocking synchronization apart from joining other tasks or
53 < * using synchronizers such as Phasers that are advertised to
54 < * cooperate with fork/join scheduling. Tasks should also not perform
55 < * blocking IO, and should ideally access variables that are
56 < * completely independent of those accessed by other running
57 < * tasks. Minor breaches of these restrictions, for example using
58 < * shared output streams, may be tolerable in practice, but frequent
59 < * use may result in poor performance, and the potential to
60 < * indefinitely stall if the number of threads not waiting for IO or
61 < * other external synchronization becomes exhausted. This usage
62 < * restriction is in part enforced by not permitting checked
63 < * exceptions such as {@code IOExceptions} to be thrown. However,
64 < * computations may still encounter unchecked exceptions, that are
65 < * rethrown to callers attempting to join them. These exceptions may
66 < * additionally include {@link RejectedExecutionException} stemming
67 < * from internal resource exhaustion, such as failure to allocate
68 < * internal task queues. Rethrown exceptions behave in the same way as
69 < * regular exceptions, but, when possible, contain stack traces (as
70 < * displayed for example using {@code ex.printStackTrace()}) of both
71 < * the thread that initiated the computation as well as the thread
72 < * actually encountering the exception; minimally only the latter.
51 > * ideally avoid {@code synchronized} methods or blocks, and should
52 > * minimize other blocking synchronization apart from joining other
53 > * tasks or using synchronizers such as Phasers that are advertised to
54 > * cooperate with fork/join scheduling. Subdividable tasks should also
55 > * not perform blocking IO, and should ideally access variables that
56 > * are completely independent of those accessed by other running
57 > * tasks. These guidelines are loosely enforced by not permitting
58 > * checked exceptions such as {@code IOExceptions} to be
59 > * thrown. However, computations may still encounter unchecked
60 > * exceptions, that are rethrown to callers attempting to join
61 > * them. These exceptions may additionally include {@link
62 > * RejectedExecutionException} stemming from internal resource
63 > * exhaustion, such as failure to allocate internal task
64 > * queues. Rethrown exceptions behave in the same way as regular
65 > * exceptions, but, when possible, contain stack traces (as displayed
66 > * for example using {@code ex.printStackTrace()}) of both the thread
67 > * that initiated the computation as well as the thread actually
68 > * encountering the exception; minimally only the latter.
69 > *
70 > * <p>It is possible to define and use ForkJoinTasks that may block,
71 > * but doing do requires three further considerations: (1) Completion
72 > * of few if any <em>other</em> tasks should be dependent on a task
73 > * that blocks on external synchronization or IO. Event-style async
74 > * tasks that are never joined often fall into this category.  (2) To
75 > * minimize resource impact, tasks should be small; ideally performing
76 > * only the (possibly) blocking action. (3) Unless the {@link
77 > * ForkJoinPool.ManagedBlocker} API is used, or the number of possibly
78 > * blocked tasks is known to be less than the pool's {@link
79 > * ForkJoinPool#getParallelism} level, the pool cannot guarantee that
80 > * enough threads will be available to ensure progress or good
81 > * performance.
82   *
83   * <p>The primary method for awaiting completion and extracting
84   * results of a task is {@link #join}, but there are several variants:
# Line 85 | Line 94 | import java.lang.reflect.Constructor;
94   * performs the most common form of parallel invocation: forking a set
95   * of tasks and joining them all.
96   *
97 + * <p>In the most typical usages, a fork-join pair act like a a call
98 + * (fork) and return (join) from a parallel recursive function. As is
99 + * the case with other forms of recursive calls, returns (joins)
100 + * should be performed innermost-first. For example, {@code a.fork();
101 + * b.fork(); b.join(); a.join();} is likely to be substantially more
102 + * efficient than joining {@code a} before {@code b}.
103 + *
104   * <p>The execution status of tasks may be queried at several levels
105   * of detail: {@link #isDone} is true if a task completed in any way
106   * (including the case where a task was cancelled without executing);
# Line 121 | Line 137 | import java.lang.reflect.Constructor;
137   * supports other methods and techniques (for example the use of
138   * {@link Phaser}, {@link #helpQuiesce}, and {@link #complete}) that
139   * may be of use in constructing custom subclasses for problems that
140 < * are not statically structured as DAGs.
140 > * are not statically structured as DAGs. To support such usages a
141 > * ForkJoinTask may be atomically <em>marked</em> using {@link
142 > * #markForkJoinTask} and checked for marking using {@link
143 > * #isMarkedForkJoinTask}. The ForkJoinTask implementation does not
144 > * use these {@code protected} methods or marks for any purpose, but
145 > * they may be of use in the construction of specialized subclasses.
146 > * For example, parallel graph traversals can use the supplied methods
147 > * to avoid revisiting nodes/tasks that have already been
148 > * processed. Also, completion based designs can use them to record
149 > * that one subtask has completed. (Method names for marking are bulky
150 > * in part to encourage definition of methods that reflect their usage
151 > * patterns.)
152   *
153   * <p>Most base support methods are {@code final}, to prevent
154   * overriding of implementations that are intrinsically tied to the
# Line 171 | Line 198 | public abstract class ForkJoinTask<V> im
198       * methods in a way that flows well in javadocs.
199       */
200  
201 +    /**
202 +     * The number of times to try to help join a task without any
203 +     * apparent progress before giving up and blocking. The value is
204 +     * arbitrary but should be large enough to cope with transient
205 +     * stalls (due to GC etc) that can cause helping methods not to be
206 +     * able to proceed because other workers have not progressed to
207 +     * the point where subtasks can be found or taken.
208 +     */
209 +    private static final int HELP_RETRIES = 32;
210 +
211      /*
212       * The status field holds run control status bits packed into a
213       * single int to minimize footprint and to ensure atomicity (via
# Line 190 | Line 227 | public abstract class ForkJoinTask<V> im
227  
228      /** The run status of this task */
229      volatile int status; // accessed directly by pool and workers
230 <    private static final int NORMAL      = -1;
231 <    private static final int CANCELLED   = -2;
232 <    private static final int EXCEPTIONAL = -3;
233 <    private static final int SIGNAL      =  1;
230 >    static final int NORMAL      = 0xfffffffc;  // negative with low 2 bits 0
231 >    static final int CANCELLED   = 0xfffffff8;  // must be < NORMAL
232 >    static final int EXCEPTIONAL = 0xfffffff4;  // must be < CANCELLED
233 >    static final int SIGNAL      = 0x00000001;
234 >    static final int MARKED      = 0x00000002;
235  
236      /**
237 <     * Marks completion and wakes up threads waiting to join this task,
238 <     * also clearing signal request bits.
237 >     * Marks completion and wakes up threads waiting to join this
238 >     * task, also clearing signal request bits. A specialization for
239 >     * NORMAL completion is in method doExec
240       *
241       * @param completion one of NORMAL, CANCELLED, EXCEPTIONAL
242       * @return completion status on exit
# Line 206 | Line 245 | public abstract class ForkJoinTask<V> im
245          for (int s;;) {
246              if ((s = status) < 0)
247                  return s;
248 <            if (UNSAFE.compareAndSwapInt(this, statusOffset, s, completion)) {
249 <                if (s != 0)
248 >            if (U.compareAndSwapInt(this, STATUS, s, (s & ~SIGNAL)|completion)) {
249 >                if ((s & SIGNAL) != 0)
250                      synchronized (this) { notifyAll(); }
251                  return completion;
252              }
# Line 215 | Line 254 | public abstract class ForkJoinTask<V> im
254      }
255  
256      /**
257 <     * Tries to block a worker thread until completed or timed out.
258 <     * Uses Object.wait time argument conventions.
259 <     * May fail on contention or interrupt.
257 >     * Primary execution method for stolen tasks. Unless done, calls
258 >     * exec and records status if completed, but doesn't wait for
259 >     * completion otherwise.
260       *
261 <     * @param millis if > 0, wait time.
261 >     * @return status on exit from this method
262       */
263 <    final void tryAwaitDone(long millis) {
264 <        int s;
265 <        try {
266 <            if (((s = status) > 0 ||
267 <                 (s == 0 &&
268 <                  UNSAFE.compareAndSwapInt(this, statusOffset, 0, SIGNAL))) &&
269 <                status > 0) {
270 <                synchronized (this) {
271 <                    if (status > 0)
272 <                        wait(millis);
263 >    final int doExec() {
264 >        int s; boolean completed;
265 >        if ((s = status) >= 0) {
266 >            try {
267 >                completed = exec();
268 >            } catch (Throwable rex) {
269 >                return setExceptionalCompletion(rex);
270 >            }
271 >            while ((s = status) >= 0 && completed) {
272 >                if (U.compareAndSwapInt(this, STATUS, s, (s & ~SIGNAL)|NORMAL)) {
273 >                    if ((s & SIGNAL) != 0)
274 >                        synchronized (this) { notifyAll(); }
275 >                    return NORMAL;
276                  }
277              }
236        } catch (InterruptedException ie) {
237            // caller must check termination
278          }
279 +        return s;
280      }
281  
282      /**
# Line 248 | Line 289 | public abstract class ForkJoinTask<V> im
289              boolean interrupted = false;
290              synchronized (this) {
291                  while ((s = status) >= 0) {
292 <                    if (s == 0)
252 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
253 <                                                 0, SIGNAL);
254 <                    else {
292 >                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
293                          try {
294                              wait();
295                          } catch (InterruptedException ie) {
# Line 277 | Line 315 | public abstract class ForkJoinTask<V> im
315          if ((s = status) >= 0) {
316              synchronized (this) {
317                  while ((s = status) >= 0) {
318 <                    if (s == 0)
281 <                        UNSAFE.compareAndSwapInt(this, statusOffset,
282 <                                                 0, SIGNAL);
283 <                    else {
318 >                    if (U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
319                          wait(millis);
320                          if (millis > 0L)
321                              break;
# Line 291 | Line 326 | public abstract class ForkJoinTask<V> im
326          return s;
327      }
328  
329 +
330      /**
331 <     * Primary execution method for stolen tasks. Unless done, calls
332 <     * exec and records status if completed, but doesn't wait for
333 <     * completion otherwise.
331 >     * Implementation for join, get, quietlyJoin. Directly handles
332 >     * only cases of already-completed, external wait, and
333 >     * unfork+exec.  Others are relayed to awaitJoin.
334 >     *
335 >     * @return status upon completion
336       */
337 <    final void doExec() {
338 <        if (status >= 0) {
339 <            boolean completed;
340 <            try {
341 <                completed = exec();
342 <            } catch (Throwable rex) {
343 <                setExceptionalCompletion(rex);
344 <                return;
307 <            }
308 <            if (completed)
309 <                setCompletion(NORMAL); // must be outside try block
337 >    private int doJoin() {
338 >        int s; Thread t; ForkJoinWorkerThread wt; ForkJoinPool.WorkQueue w;
339 >        if ((s = status) >= 0) {
340 >            if (!((t = Thread.currentThread()) instanceof ForkJoinWorkerThread))
341 >                s = externalAwaitDone();
342 >            else if (!(w = (wt = (ForkJoinWorkerThread)t).workQueue).
343 >                     tryUnpush(this) || (s = doExec()) >= 0)
344 >                s = awaitJoin(w, wt.pool);
345          }
346 +        return s;
347      }
348  
349      /**
350 <     * Primary mechanics for join, get, quietlyJoin.
350 >     * Helps and/or blocks until joined.
351 >     *
352 >     * @param w the joiner
353 >     * @param p the pool
354       * @return status upon completion
355       */
356 <    private int doJoin() {
357 <        Thread t; ForkJoinWorkerThread w; int s; boolean completed;
358 <        if ((t = Thread.currentThread()) instanceof ForkJoinWorkerThread) {
359 <            if ((s = status) < 0)
360 <                return s;
361 <            if ((w = (ForkJoinWorkerThread)t).unpushTask(this)) {
356 >    private int awaitJoin(ForkJoinPool.WorkQueue w, ForkJoinPool p) {
357 >        int s;
358 >        ForkJoinTask<?> prevJoin = w.currentJoin;
359 >        w.currentJoin = this;
360 >        for (int k = HELP_RETRIES; (s = status) >= 0;) {
361 >            if ((w.queueSize() > 0) ?
362 >                w.tryRemoveAndExec(this) :        // self-help
363 >                p.tryHelpStealer(w, this))        // help process tasks
364 >                k = HELP_RETRIES;                 // reset if made progress
365 >            else if ((s = status) < 0)            // recheck
366 >                break;
367 >            else if (--k > 0) {
368 >                if ((k & 3) == 1)
369 >                    Thread.yield();               // occasionally yield
370 >            }
371 >            else if (k == 0)
372 >                p.tryPollForAndExec(w, this);     // uncommon self-help case
373 >            else if (p.tryCompensate()) {         // true if can block
374                  try {
375 <                    completed = exec();
376 <                } catch (Throwable rex) {
377 <                    return setExceptionalCompletion(rex);
375 >                    int ss = status;
376 >                    if (ss >= 0 &&                // assert need signal
377 >                        U.compareAndSwapInt(this, STATUS, ss, ss | SIGNAL)) {
378 >                        synchronized (this) {
379 >                            if (status >= 0)      // block
380 >                                wait();
381 >                        }
382 >                    }
383 >                } catch (InterruptedException ignore) {
384 >                } finally {
385 >                    p.incrementActiveCount();     // re-activate
386                  }
328                if (completed)
329                    return setCompletion(NORMAL);
387              }
331            return w.joinTask(this);
388          }
389 <        else
390 <            return externalAwaitDone();
389 >        w.currentJoin = prevJoin;
390 >        return s;
391      }
392  
393      /**
394 <     * Primary mechanics for invoke, quietlyInvoke.
394 >     * Implementation for invoke, quietlyInvoke.
395 >     *
396       * @return status upon completion
397       */
398      private int doInvoke() {
399 <        int s; boolean completed;
400 <        if ((s = status) < 0)
399 >        int s;
400 >        if ((s = doExec()) < 0)
401              return s;
345        try {
346            completed = exec();
347        } catch (Throwable rex) {
348            return setExceptionalCompletion(rex);
349        }
350        if (completed)
351            return setCompletion(NORMAL);
402          else
403              return doJoin();
404      }
# Line 425 | Line 475 | public abstract class ForkJoinTask<V> im
475      }
476  
477      /**
478 +     * Cancels, ignoring any exceptions thrown by cancel. Used during
479 +     * worker and pool shutdown. Cancel is spec'ed not to throw any
480 +     * exceptions, but if it does anyway, we have no recourse during
481 +     * shutdown, so guard against this case.
482 +     */
483 +    static final void cancelIgnoringExceptions(ForkJoinTask<?> t) {
484 +        if (t != null && t.status >= 0) {
485 +            try {
486 +                t.cancel(false);
487 +            } catch (Throwable ignore) {
488 +            }
489 +        }
490 +    }
491 +
492 +    /**
493       * Removes exception node and clears status
494       */
495      private void clearExceptionalCompletion() {
# Line 563 | Line 628 | public abstract class ForkJoinTask<V> im
628          if ((s = status) == CANCELLED)
629              throw new CancellationException();
630          if (s == EXCEPTIONAL && (ex = getThrowableException()) != null)
631 <            UNSAFE.throwException(ex);
631 >            U.throwException(ex);
632          return getRawResult();
633      }
634  
# Line 588 | Line 653 | public abstract class ForkJoinTask<V> im
653       * @return {@code this}, to simplify usage
654       */
655      public final ForkJoinTask<V> fork() {
656 <        ((ForkJoinWorkerThread) Thread.currentThread())
657 <            .pushTask(this);
656 >        ForkJoinWorkerThread wt;
657 >        (wt = (ForkJoinWorkerThread)Thread.currentThread()).
658 >            workQueue.push(this, wt.pool);
659          return this;
660      }
661  
# Line 700 | Line 766 | public abstract class ForkJoinTask<V> im
766              }
767          }
768          if (ex != null)
769 <            UNSAFE.throwException(ex);
769 >            U.throwException(ex);
770      }
771  
772      /**
# Line 757 | Line 823 | public abstract class ForkJoinTask<V> im
823              }
824          }
825          if (ex != null)
826 <            UNSAFE.throwException(ex);
826 >            U.throwException(ex);
827          return tasks;
828      }
829  
# Line 792 | Line 858 | public abstract class ForkJoinTask<V> im
858          return setCompletion(CANCELLED) == CANCELLED;
859      }
860  
795    /**
796     * Cancels, ignoring any exceptions thrown by cancel. Used during
797     * worker and pool shutdown. Cancel is spec'ed not to throw any
798     * exceptions, but if it does anyway, we have no recourse during
799     * shutdown, so guard against this case.
800     */
801    final void cancelIgnoringExceptions() {
802        try {
803            cancel(false);
804        } catch (Throwable ignore) {
805        }
806    }
807
861      public final boolean isDone() {
862          return status < 0;
863      }
# Line 928 | Line 981 | public abstract class ForkJoinTask<V> im
981       */
982      public final V get(long timeout, TimeUnit unit)
983          throws InterruptedException, ExecutionException, TimeoutException {
984 +        // Messy in part because we measure in nanos, but wait in millis
985 +        int s; long millis, nanos;
986          Thread t = Thread.currentThread();
987 <        if (t instanceof ForkJoinWorkerThread) {
988 <            ForkJoinWorkerThread w = (ForkJoinWorkerThread) t;
989 <            long nanos = unit.toNanos(timeout);
990 <            if (status >= 0) {
991 <                boolean completed = false;
992 <                if (w.unpushTask(this)) {
993 <                    try {
994 <                        completed = exec();
995 <                    } catch (Throwable rex) {
996 <                        setExceptionalCompletion(rex);
987 >        if (!(t instanceof ForkJoinWorkerThread)) {
988 >            if ((millis = unit.toMillis(timeout)) > 0L)
989 >                s = externalInterruptibleAwaitDone(millis);
990 >            else
991 >                s = status;
992 >        }
993 >        else if ((s = status) >= 0 && (nanos = unit.toNanos(timeout)) > 0L) {
994 >            long deadline = System.nanoTime() + nanos;
995 >            ForkJoinWorkerThread wt = (ForkJoinWorkerThread)t;
996 >            ForkJoinPool.WorkQueue w = wt.workQueue;
997 >            ForkJoinPool p = wt.pool;
998 >            if (w.tryUnpush(this))
999 >                doExec();
1000 >            boolean blocking = false;
1001 >            try {
1002 >                while ((s = status) >= 0) {
1003 >                    if (w.runState < 0)
1004 >                        cancelIgnoringExceptions(this);
1005 >                    else if (!blocking)
1006 >                        blocking = p.tryCompensate();
1007 >                    else {
1008 >                        millis = TimeUnit.NANOSECONDS.toMillis(nanos);
1009 >                        if (millis > 0L &&
1010 >                            U.compareAndSwapInt(this, STATUS, s, s | SIGNAL)) {
1011 >                            try {
1012 >                                synchronized (this) {
1013 >                                    if (status >= 0)
1014 >                                        wait(millis);
1015 >                                }
1016 >                            } catch (InterruptedException ie) {
1017 >                            }
1018 >                        }
1019 >                        if ((s = status) < 0 ||
1020 >                            (nanos = deadline - System.nanoTime()) <= 0L)
1021 >                            break;
1022                      }
1023                  }
1024 <                if (completed)
1025 <                    setCompletion(NORMAL);
1026 <                else if (status >= 0 && nanos > 0)
947 <                    w.pool.timedAwaitJoin(this, nanos);
1024 >            } finally {
1025 >                if (blocking)
1026 >                    p.incrementActiveCount();
1027              }
1028          }
950        else {
951            long millis = unit.toMillis(timeout);
952            if (millis > 0)
953                externalInterruptibleAwaitDone(millis);
954        }
955        int s = status;
1029          if (s != NORMAL) {
1030              Throwable ex;
1031              if (s == CANCELLED)
# Line 998 | Line 1071 | public abstract class ForkJoinTask<V> im
1071       * ClassCastException}.
1072       */
1073      public static void helpQuiesce() {
1074 <        ((ForkJoinWorkerThread) Thread.currentThread())
1075 <            .helpQuiescePool();
1074 >        ForkJoinWorkerThread w =
1075 >            (ForkJoinWorkerThread)Thread.currentThread();
1076 >        w.pool.helpQuiescePool(w.workQueue);
1077      }
1078  
1079      /**
# Line 1067 | Line 1141 | public abstract class ForkJoinTask<V> im
1141       * @return {@code true} if unforked
1142       */
1143      public boolean tryUnfork() {
1144 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1145 <            .unpushTask(this);
1144 >        return ((ForkJoinWorkerThread)Thread.currentThread())
1145 >            .workQueue.tryUnpush(this);
1146      }
1147  
1148      /**
# Line 1087 | Line 1161 | public abstract class ForkJoinTask<V> im
1161       */
1162      public static int getQueuedTaskCount() {
1163          return ((ForkJoinWorkerThread) Thread.currentThread())
1164 <            .getQueueSize();
1164 >            .workQueue.queueSize();
1165      }
1166  
1167      /**
# Line 1109 | Line 1183 | public abstract class ForkJoinTask<V> im
1183       * @return the surplus number of tasks, which may be negative
1184       */
1185      public static int getSurplusQueuedTaskCount() {
1186 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1187 <            .getEstimatedSurplusTaskCount();
1186 >        /*
1187 >         * The aim of this method is to return a cheap heuristic guide
1188 >         * for task partitioning when programmers, frameworks, tools,
1189 >         * or languages have little or no idea about task granularity.
1190 >         * In essence by offering this method, we ask users only about
1191 >         * tradeoffs in overhead vs expected throughput and its
1192 >         * variance, rather than how finely to partition tasks.
1193 >         *
1194 >         * In a steady state strict (tree-structured) computation,
1195 >         * each thread makes available for stealing enough tasks for
1196 >         * other threads to remain active. Inductively, if all threads
1197 >         * play by the same rules, each thread should make available
1198 >         * only a constant number of tasks.
1199 >         *
1200 >         * The minimum useful constant is just 1. But using a value of
1201 >         * 1 would require immediate replenishment upon each steal to
1202 >         * maintain enough tasks, which is infeasible.  Further,
1203 >         * partitionings/granularities of offered tasks should
1204 >         * minimize steal rates, which in general means that threads
1205 >         * nearer the top of computation tree should generate more
1206 >         * than those nearer the bottom. In perfect steady state, each
1207 >         * thread is at approximately the same level of computation
1208 >         * tree. However, producing extra tasks amortizes the
1209 >         * uncertainty of progress and diffusion assumptions.
1210 >         *
1211 >         * So, users will want to use values larger, but not much
1212 >         * larger than 1 to both smooth over transient shortages and
1213 >         * hedge against uneven progress; as traded off against the
1214 >         * cost of extra task overhead. We leave the user to pick a
1215 >         * threshold value to compare with the results of this call to
1216 >         * guide decisions, but recommend values such as 3.
1217 >         *
1218 >         * When all threads are active, it is on average OK to
1219 >         * estimate surplus strictly locally. In steady-state, if one
1220 >         * thread is maintaining say 2 surplus tasks, then so are
1221 >         * others. So we can just use estimated queue length.
1222 >         * However, this strategy alone leads to serious mis-estimates
1223 >         * in some non-steady-state conditions (ramp-up, ramp-down,
1224 >         * other stalls). We can detect many of these by further
1225 >         * considering the number of "idle" threads, that are known to
1226 >         * have zero queued tasks, so compensate by a factor of
1227 >         * (#idle/#active) threads.
1228 >         */
1229 >        ForkJoinWorkerThread w =
1230 >            (ForkJoinWorkerThread)Thread.currentThread();
1231 >        return w.workQueue.queueSize() - w.pool.idlePerActive();
1232      }
1233  
1234      // Extension methods
# Line 1167 | Line 1285 | public abstract class ForkJoinTask<V> im
1285       * @return the next task, or {@code null} if none are available
1286       */
1287      protected static ForkJoinTask<?> peekNextLocalTask() {
1288 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1171 <            .peekTask();
1288 >        return ((ForkJoinWorkerThread) Thread.currentThread()).workQueue.peek();
1289      }
1290  
1291      /**
# Line 1187 | Line 1304 | public abstract class ForkJoinTask<V> im
1304       */
1305      protected static ForkJoinTask<?> pollNextLocalTask() {
1306          return ((ForkJoinWorkerThread) Thread.currentThread())
1307 <            .pollLocalTask();
1307 >            .workQueue.nextLocalTask();
1308      }
1309  
1310      /**
# Line 1209 | Line 1326 | public abstract class ForkJoinTask<V> im
1326       * @return a task, or {@code null} if none are available
1327       */
1328      protected static ForkJoinTask<?> pollTask() {
1329 <        return ((ForkJoinWorkerThread) Thread.currentThread())
1330 <            .pollTask();
1329 >        ForkJoinWorkerThread w =
1330 >            (ForkJoinWorkerThread)Thread.currentThread();
1331 >        return w.pool.nextTaskFor(w.workQueue);
1332 >    }
1333 >
1334 >    // Mark-bit operations
1335 >
1336 >    /**
1337 >     * Returns true if this task is marked.
1338 >     *
1339 >     * @return true if this task is marked
1340 >     * @since 1.8
1341 >     */
1342 >    public final boolean isMarkedForkJoinTask() {
1343 >        return (status & MARKED) != 0;
1344 >    }
1345 >
1346 >    /**
1347 >     * Atomically sets the mark on this task.
1348 >     *
1349 >     * @return true if this task was previously unmarked
1350 >     * @since 1.8
1351 >     */
1352 >    public final boolean markForkJoinTask() {
1353 >        for (int s;;) {
1354 >            if (((s = status) & MARKED) != 0)
1355 >                return false;
1356 >            if (U.compareAndSwapInt(this, STATUS, s, s | MARKED))
1357 >                return true;
1358 >        }
1359 >    }
1360 >
1361 >    /**
1362 >     * Atomically clears the mark on this task.
1363 >     *
1364 >     * @return true if this task was previously marked
1365 >     * @since 1.8
1366 >     */
1367 >    public final boolean unmarkForkJoinTask() {
1368 >        for (int s;;) {
1369 >            if (((s = status) & MARKED) == 0)
1370 >                return false;
1371 >            if (U.compareAndSwapInt(this, STATUS, s, s & ~MARKED))
1372 >                return true;
1373 >        }
1374      }
1375  
1376      /**
# Line 1334 | Line 1494 | public abstract class ForkJoinTask<V> im
1494      }
1495  
1496      // Unsafe mechanics
1497 <    private static final sun.misc.Unsafe UNSAFE;
1498 <    private static final long statusOffset;
1497 >    private static final sun.misc.Unsafe U;
1498 >    private static final long STATUS;
1499      static {
1500          exceptionTableLock = new ReentrantLock();
1501          exceptionTableRefQueue = new ReferenceQueue<Object>();
1502          exceptionTable = new ExceptionNode[EXCEPTION_MAP_CAPACITY];
1503          try {
1504 <            UNSAFE = sun.misc.Unsafe.getUnsafe();
1505 <            statusOffset = UNSAFE.objectFieldOffset
1504 >            U = sun.misc.Unsafe.getUnsafe();
1505 >            STATUS = U.objectFieldOffset
1506                  (ForkJoinTask.class.getDeclaredField("status"));
1507          } catch (Exception e) {
1508              throw new Error(e);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines