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

Comparing jsr166/src/jsr166y/ForkJoinWorkerThread.java (file contents):
Revision 1.33 by dl, Thu May 27 16:46:49 2010 UTC vs.
Revision 1.40 by dl, Wed Aug 11 18:45:12 2010 UTC

# Line 83 | Line 83 | public class ForkJoinWorkerThread extend
83       * by the ForkJoinPool).  This allows use in message-passing
84       * frameworks in which tasks are never joined.
85       *
86 <     * Efficient implementation of this approach currently relies on
87 <     * an uncomfortable amount of "Unsafe" mechanics. To maintain
86 >     * When a worker would otherwise be blocked waiting to join a
87 >     * task, it first tries a form of linear helping: Each worker
88 >     * records (in field currentSteal) the most recent task it stole
89 >     * from some other worker. Plus, it records (in field currentJoin)
90 >     * the task it is currently actively joining. Method joinTask uses
91 >     * these markers to try to find a worker to help (i.e., steal back
92 >     * a task from and execute it) that could hasten completion of the
93 >     * actively joined task. In essence, the joiner executes a task
94 >     * that would be on its own local deque had the to-be-joined task
95 >     * not been stolen. This may be seen as a conservative variant of
96 >     * the approach in Wagner & Calder "Leapfrogging: a portable
97 >     * technique for implementing efficient futures" SIGPLAN Notices,
98 >     * 1993 (http://portal.acm.org/citation.cfm?id=155354). It differs
99 >     * in that: (1) We only maintain dependency links across workers
100 >     * upon steals, rather than use per-task bookkeeping.  This may
101 >     * require a linear scan of workers array to locate stealers, but
102 >     * usually doesn't because stealers leave hints (that may become
103 >     * stale/wrong) of where to locate them. This isolates cost to
104 >     * when it is needed, rather than adding to per-task overhead.
105 >     * (2) It is "shallow", ignoring nesting and potentially cyclic
106 >     * mutual steals.  (3) It is intentionally racy: field currentJoin
107 >     * is updated only while actively joining, which means that we
108 >     * miss links in the chain during long-lived tasks, GC stalls etc
109 >     * (which is OK since blocking in such cases is usually a good
110 >     * idea).  (4) We bound the number of attempts to find work (see
111 >     * MAX_HELP_DEPTH) and fall back to suspending the worker and if
112 >     * necessary replacing it with a spare (see
113 >     * ForkJoinPool.tryAwaitJoin).
114 >     *
115 >     * Efficient implementation of these algorithms currently relies
116 >     * on an uncomfortable amount of "Unsafe" mechanics. To maintain
117       * correct orderings, reads and writes of variable base require
118       * volatile ordering.  Variable sp does not require volatile
119       * writes but still needs store-ordering, which we accomplish by
120       * pre-incrementing sp before filling the slot with an ordered
121       * store.  (Pre-incrementing also enables backouts used in
122 <     * scanWhileJoining.)  Because they are protected by volatile base
123 <     * reads, reads of the queue array and its slots by other threads
124 <     * do not need volatile load semantics, but writes (in push)
125 <     * require store order and CASes (in pop and deq) require
126 <     * (volatile) CAS semantics.  (Michael, Saraswat, and Vechev's
127 <     * algorithm has similar properties, but without support for
128 <     * nulling slots.)  Since these combinations aren't supported
129 <     * using ordinary volatiles, the only way to accomplish these
130 <     * efficiently is to use direct Unsafe calls. (Using external
131 <     * AtomicIntegers and AtomicReferenceArrays for the indices and
132 <     * array is significantly slower because of memory locality and
133 <     * indirection effects.)
122 >     * joinTask.)  Because they are protected by volatile base reads,
123 >     * reads of the queue array and its slots by other threads do not
124 >     * need volatile load semantics, but writes (in push) require
125 >     * store order and CASes (in pop and deq) require (volatile) CAS
126 >     * semantics.  (Michael, Saraswat, and Vechev's algorithm has
127 >     * similar properties, but without support for nulling slots.)
128 >     * Since these combinations aren't supported using ordinary
129 >     * volatiles, the only way to accomplish these efficiently is to
130 >     * use direct Unsafe calls. (Using external AtomicIntegers and
131 >     * AtomicReferenceArrays for the indices and array is
132 >     * significantly slower because of memory locality and indirection
133 >     * effects.)
134       *
135       * Further, performance on most platforms is very sensitive to
136       * placement and sizing of the (resizable) queue array.  Even
# Line 126 | Line 155 | public class ForkJoinWorkerThread extend
155      private static final Random seedGenerator = new Random();
156  
157      /**
158 <     * The timeout value for suspending spares. Spare workers that
159 <     * remain unsignalled for more than this time may be trimmed
160 <     * (killed and removed from pool).  Since our goal is to avoid
161 <     * long-term thread buildup, the exact value of timeout does not
162 <     * matter too much so long as it avoids most false-alarm timeouts
163 <     * under GC stalls or momentarily high system load.
158 >     * The maximum stolen->joining link depth allowed in helpJoinTask.
159 >     * Depths for legitimate chains are unbounded, but we use a fixed
160 >     * constant to avoid (otherwise unchecked) cycles and bound
161 >     * staleness of traversal parameters at the expense of sometimes
162 >     * blocking when we could be helping.
163 >     */
164 >    private static final int MAX_HELP_DEPTH = 8;
165 >
166 >    /**
167 >     * The wakeup interval (in nanoseconds) for the first worker
168 >     * suspended as spare.  On each wakeup not signalled by a
169 >     * resumption, it may ask the pool to reduce the number of spares.
170       */
171 <    private static final long SPARE_KEEPALIVE_NANOS =
137 <        5L * 1000L * 1000L * 1000L; // 5 secs
171 >    private static final long TRIM_RATE_NANOS = 200L * 1000L * 1000L;
172  
173      /**
174       * Capacity of work-stealing queue array upon initialization.
175 <     * Must be a power of two. Initial size must be at least 2, but is
175 >     * Must be a power of two. Initial size must be at least 4, but is
176       * padded to minimize cache effects.
177       */
178      private static final int INITIAL_QUEUE_CAPACITY = 1 << 13;
# Line 178 | Line 212 | public class ForkJoinWorkerThread extend
212      private int sp;
213  
214      /**
215 +     * The index of most recent stealer, used as a hint to avoid
216 +     * traversal in method helpJoinTask. This is only a hint because a
217 +     * worker might have had multiple steals and this only holds one
218 +     * of them (usually the most current). Declared non-volatile,
219 +     * relying on other prevailing sync to keep reasonably current.
220 +     */
221 +    private int stealHint;
222 +
223 +    /**
224       * Run state of this worker. In addition to the usual run levels,
225       * tracks if this worker is suspended as a spare, and if it was
226       * killed (trimmed) while suspended. However, "active" status is
# Line 191 | Line 234 | public class ForkJoinWorkerThread extend
234      private static final int TRIMMED     = 0x08; // killed while suspended
235  
236      /**
194     * Number of LockSupport.park calls to block this thread for
195     * suspension or event waits. Used for internal instrumention;
196     * currently not exported but included because volatile write upon
197     * park also provides a workaround for a JVM bug.
198     */
199    private volatile int parkCount;
200
201    /**
237       * Number of steals, transferred and reset in pool callbacks pool
238       * when idle Accessed directly by pool.
239       */
# Line 218 | Line 253 | public class ForkJoinWorkerThread extend
253  
254      /**
255       * True if use local fifo, not default lifo, for local polling.
256 <     * Shadows value from ForkJoinPool, which resets it if changed
222 <     * pool-wide.
256 >     * Shadows value from ForkJoinPool.
257       */
258 <    private boolean locallyFifo;
258 >    private final boolean locallyFifo;
259  
260      /**
261       * Index of this worker in pool array. Set once by pool before
# Line 243 | Line 277 | public class ForkJoinWorkerThread extend
277      volatile long nextWaiter;
278  
279      /**
280 +     * Number of times this thread suspended as spare
281 +     */
282 +    int spareCount;
283 +
284 +    /**
285 +     * Encoded index and count of next spare waiter. Used only
286 +     * by ForkJoinPool for managing spares.
287 +     */
288 +    volatile int nextSpare;
289 +
290 +    /**
291 +     * The task currently being joined, set only when actively trying
292 +     * to helpStealer. Written only by current thread, but read by
293 +     * others.
294 +     */
295 +    private volatile ForkJoinTask<?> currentJoin;
296 +
297 +    /**
298 +     * The task most recently stolen from another worker (or
299 +     * submission queue).  Not volatile because always read/written in
300 +     * presence of related volatiles in those cases where it matters.
301 +     */
302 +    private ForkJoinTask<?> currentSteal;
303 +
304 +    /**
305       * Creates a ForkJoinWorkerThread operating in the given pool.
306       *
307       * @param pool the pool this thread works in
308       * @throws NullPointerException if pool is null
309       */
310      protected ForkJoinWorkerThread(ForkJoinPool pool) {
252        if (pool == null) throw new NullPointerException();
311          this.pool = pool;
312 +        this.locallyFifo = pool.locallyFifo;
313 +        setDaemon(true);
314          // To avoid exposing construction details to subclasses,
315          // remaining initialization is in start() and onStart()
316      }
# Line 258 | Line 318 | public class ForkJoinWorkerThread extend
318      /**
319       * Performs additional initialization and starts this thread
320       */
321 <    final void start(int poolIndex, boolean locallyFifo,
262 <                     UncaughtExceptionHandler ueh) {
321 >    final void start(int poolIndex, UncaughtExceptionHandler ueh) {
322          this.poolIndex = poolIndex;
264        this.locallyFifo = locallyFifo;
323          if (ueh != null)
324              setUncaughtExceptionHandler(ueh);
267        setDaemon(true);
325          start();
326      }
327  
# Line 305 | Line 362 | public class ForkJoinWorkerThread extend
362          int rs = seedGenerator.nextInt();
363          seed = rs == 0? 1 : rs; // seed must be nonzero
364  
365 <        // Allocate name string and queue array in this thread
365 >        // Allocate name string and arrays in this thread
366          String pid = Integer.toString(pool.getPoolNumber());
367          String wid = Integer.toString(poolIndex);
368          setName("ForkJoinPool-" + pid + "-worker-" + wid);
# Line 324 | Line 381 | public class ForkJoinWorkerThread extend
381      protected void onTermination(Throwable exception) {
382          try {
383              cancelTasks();
384 +            while (active)              // force inactive
385 +                active = !pool.tryDecrementActiveCount();
386              setTerminated();
387              pool.workerTerminated(this);
388          } catch (Throwable ex) {        // Shouldn't ever happen
# Line 358 | Line 417 | public class ForkJoinWorkerThread extend
417       * Find and execute tasks and check status while running
418       */
419      private void mainLoop() {
420 <        boolean ran = false; // true if ran task on previous step
420 >        int misses = 0; // track consecutive times failed to find work; max 2
421          ForkJoinPool p = pool;
422          for (;;) {
423 <            p.preStep(this, ran);
423 >            p.preStep(this, misses);
424              if (runState != 0)
425 <                return;
426 <            ForkJoinTask<?> t; // try to get and run stolen or submitted task
427 <            if (ran = (t = scan()) != null || (t = pollSubmission()) != null) {
369 <                t.tryExec();
370 <                if (base != sp)
371 <                    runLocalTasks();
372 <            }
425 >                break;
426 >            misses = ((tryExecSteal() || tryExecSubmission()) ? 0 :
427 >                      (misses < 2 ? misses + 1 : 2));
428          }
429      }
430  
431      /**
432 <     * Runs local tasks until queue is empty or shut down.  Call only
433 <     * while active.
432 >     * Try to steal a task and execute it
433 >     *
434 >     * @return true if ran a task
435       */
436 <    private void runLocalTasks() {
437 <        while (runState == 0) {
438 <            ForkJoinTask<?> t = locallyFifo? locallyDeqTask() : popTask();
439 <            if (t != null)
440 <                t.tryExec();
441 <            else if (base == sp)
442 <                break;
436 >    private boolean tryExecSteal() {
437 >        ForkJoinTask<?> t;
438 >        if ((t  = scan()) != null) {
439 >            t.quietlyExec();
440 >            currentSteal = null;
441 >            if (sp != base)
442 >                execLocalTasks();
443 >            return true;
444          }
445 +        return false;
446      }
447  
448      /**
449 <     * If a submission exists, try to activate and take it
449 >     * If a submission exists, try to activate and run it;
450       *
451 <     * @return a task, if available
451 >     * @return true if ran a task
452       */
453 <    private ForkJoinTask<?> pollSubmission() {
453 >    private boolean tryExecSubmission() {
454          ForkJoinPool p = pool;
455          while (p.hasQueuedSubmissions()) {
456 +            ForkJoinTask<?> t;
457              if (active || (active = p.tryIncrementActiveCount())) {
458 <                ForkJoinTask<?> t = p.pollSubmission();
459 <                return t != null ? t : scan(); // if missed, rescan
458 >                if ((t = p.pollSubmission()) != null) {
459 >                    currentSteal = t;
460 >                    t.quietlyExec();
461 >                    currentSteal = null;
462 >                    if (sp != base)
463 >                        execLocalTasks();
464 >                    return true;
465 >                }
466              }
467          }
468 <        return null;
468 >        return false;
469 >    }
470 >
471 >    /**
472 >     * Runs local tasks until queue is empty or shut down.  Call only
473 >     * while active.
474 >     */
475 >    private void execLocalTasks() {
476 >        while (runState == 0) {
477 >            ForkJoinTask<?> t = locallyFifo? locallyDeqTask() : popTask();
478 >            if (t != null)
479 >                t.quietlyExec();
480 >            else if (sp == base)
481 >                break;
482 >        }
483      }
484  
485      /*
# Line 447 | Line 526 | public class ForkJoinWorkerThread extend
526       * @param t the task. Caller must ensure non-null.
527       */
528      final void pushTask(ForkJoinTask<?> t) {
450        int s;
529          ForkJoinTask<?>[] q = queue;
530          int mask = q.length - 1; // implicit assert q != null
531 <        UNSAFE.putOrderedObject(q, (((s = sp++) & mask) << qShift) + qBase, t);
532 <        if ((s -= base) <= 0)
533 <            pool.signalWork();
534 <        else if (s + 1 >= mask)
535 <            growQueue();
531 >        int s = sp++;            // ok to increment sp before slot write
532 >        UNSAFE.putOrderedObject(q, ((s & mask) << qShift) + qBase, t);
533 >        if ((s -= base) == 0)
534 >            pool.signalWork();   // was empty
535 >        else if (s == mask)
536 >            growQueue();         // is full
537      }
538  
539      /**
540       * Tries to take a task from the base of the queue, failing if
541       * empty or contended. Note: Specializations of this code appear
542 <     * in scan and scanWhileJoining.
542 >     * in locallyDeqTask and elsewhere.
543       *
544       * @return a task, or null if none or contended
545       */
# Line 468 | Line 547 | public class ForkJoinWorkerThread extend
547          ForkJoinTask<?> t;
548          ForkJoinTask<?>[] q;
549          int b, i;
550 <        if ((b = base) != sp &&
550 >        if (sp != (b = base) &&
551              (q = queue) != null && // must read q after b
552 <            (t = q[i = (q.length - 1) & b]) != null &&
552 >            (t = q[i = (q.length - 1) & b]) != null && base == b &&
553              UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
554              base = b + 1;
555              return t;
# Line 490 | Line 569 | public class ForkJoinWorkerThread extend
569              ForkJoinTask<?> t;
570              int b, i;
571              while (sp != (b = base)) {
572 <                if ((t = q[i = (q.length - 1) & b]) != null &&
572 >                if ((t = q[i = (q.length - 1) & b]) != null && base == b &&
573                      UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase,
574                                                  t, null)) {
575                      base = b + 1;
# Line 503 | Line 582 | public class ForkJoinWorkerThread extend
582  
583      /**
584       * Returns a popped task, or null if empty. Assumes active status.
585 <     * Called only by current thread. (Note: a specialization of this
507 <     * code appears in popWhileJoining.)
585 >     * Called only by current thread.
586       */
587 <    final ForkJoinTask<?> popTask() {
588 <        int s;
589 <        ForkJoinTask<?>[] q;
590 <        if (base != (s = sp) && (q = queue) != null) {
591 <            int i = (q.length - 1) & --s;
592 <            ForkJoinTask<?> t = q[i];
593 <            if (t != null && UNSAFE.compareAndSwapObject
594 <                (q, (i << qShift) + qBase, t, null)) {
595 <                sp = s;
596 <                return t;
587 >    private ForkJoinTask<?> popTask() {
588 >        ForkJoinTask<?>[] q = queue;
589 >        if (q != null) {
590 >            int s;
591 >            while ((s = sp) != base) {
592 >                int i = (q.length - 1) & --s;
593 >                long u = (i << qShift) + qBase; // raw offset
594 >                ForkJoinTask<?> t = q[i];
595 >                if (t == null)   // lost to stealer
596 >                    break;
597 >                if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
598 >                    sp = s; // putOrderedInt may encourage more timely write
599 >                    // UNSAFE.putOrderedInt(this, spOffset, s);
600 >                    return t;
601 >                }
602              }
603          }
604          return null;
# Line 530 | Line 613 | public class ForkJoinWorkerThread extend
613       */
614      final boolean unpushTask(ForkJoinTask<?> t) {
615          int s;
616 <        ForkJoinTask<?>[] q;
617 <        if (base != (s = sp) && (q = queue) != null &&
616 >        ForkJoinTask<?>[] q = queue;
617 >        if ((s = sp) != base && q != null &&
618              UNSAFE.compareAndSwapObject
619              (q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) {
620              sp = s;
621 +            // UNSAFE.putOrderedInt(this, spOffset, s);
622              return true;
623          }
624          return false;
# Line 623 | Line 707 | public class ForkJoinWorkerThread extend
707                  ForkJoinWorkerThread v = ws[k & mask];
708                  r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift
709                  if (v != null && v.base != v.sp) {
710 <                    int b, i;             // inline specialized deqTask
711 <                    ForkJoinTask<?>[] q;
628 <                    ForkJoinTask<?> t;
629 <                    if ((canSteal ||      // ensure active status
710 >                    ForkJoinTask<?>[] q; int b;
711 >                    if ((canSteal ||       // ensure active status
712                           (canSteal = active = p.tryIncrementActiveCount())) &&
713 <                        (q = v.queue) != null &&
714 <                        (t = q[i = (q.length - 1) & (b = v.base)]) != null &&
715 <                        UNSAFE.compareAndSwapObject
716 <                        (q, (i << qShift) + qBase, t, null)) {
717 <                        v.base = b + 1;
718 <                        seed = r;
719 <                        ++stealCount;
720 <                        return t;
713 >                        (q = v.queue) != null && (b = v.base) != v.sp) {
714 >                        int i = (q.length - 1) & b;
715 >                        long u = (i << qShift) + qBase; // raw offset
716 >                        ForkJoinTask<?> t = q[i];
717 >                        if (v.base == b && t != null &&
718 >                            UNSAFE.compareAndSwapObject(q, u, t, null)) {
719 >                            int pid = poolIndex;
720 >                            currentSteal = t;
721 >                            v.stealHint = pid;
722 >                            v.base = b + 1;
723 >                            seed = r;
724 >                            ++stealCount;
725 >                            return t;
726 >                        }
727                      }
728                      j = -n;
729                      k = r;                // restart on contention
# Line 654 | Line 742 | public class ForkJoinWorkerThread extend
742      // Run State management
743  
744      // status check methods used mainly by ForkJoinPool
745 +    final boolean isRunning()     { return runState == 0; }
746      final boolean isTerminating() { return (runState & TERMINATING) != 0; }
747      final boolean isTerminated()  { return (runState & TERMINATED) != 0; }
748      final boolean isSuspended()   { return (runState & SUSPENDED) != 0; }
749      final boolean isTrimmed()     { return (runState & TRIMMED) != 0; }
750  
751      /**
752 <     * Sets state to TERMINATING, also resuming if suspended.
752 >     * Sets state to TERMINATING, also, unless "quiet", unparking if
753 >     * not already terminated
754 >     *
755 >     * @param quiet don't unpark (used for faster status updates on
756 >     * pool termination)
757       */
758 <    final void shutdown() {
758 >    final void shutdown(boolean quiet) {
759          for (;;) {
760              int s = runState;
761 +            if ((s & (TERMINATING|TERMINATED)) != 0)
762 +                break;
763              if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended
764                  if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
765                                               (s & ~SUSPENDED) |
766 <                                             (TRIMMED|TERMINATING))) {
672 <                    LockSupport.unpark(this);
766 >                                             (TRIMMED|TERMINATING)))
767                      break;
674                }
768              }
769              else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
770                                                s | TERMINATING))
771                  break;
772          }
773 +        if (!quiet && (runState & TERMINATED) != 0)
774 +            LockSupport.unpark(this);
775      }
776  
777      /**
778 <     * Sets state to TERMINATED. Called only by this thread.
778 >     * Sets state to TERMINATED. Called only by onTermination()
779       */
780      private void setTerminated() {
781          int s;
# Line 690 | Line 785 | public class ForkJoinWorkerThread extend
785      }
786  
787      /**
788 <     * Instrumented version of park. Also used by ForkJoinPool.awaitEvent
694 <     */
695 <    final void doPark() {
696 <        ++parkCount;
697 <        LockSupport.park(this);
698 <    }
699 <
700 <    /**
701 <     * If suspended, tries to set status to unsuspended.
702 <     * Caller must unpark to actually resume
788 >     * If suspended, tries to set status to unsuspended and unparks.
789       *
790       * @return true if successful
791       */
792      final boolean tryUnsuspend() {
793          int s;
794 <        return (((s = runState) & SUSPENDED) != 0 &&
795 <                UNSAFE.compareAndSwapInt(this, runStateOffset, s,
796 <                                         s & ~SUSPENDED));
794 >        while (((s = runState) & SUSPENDED) != 0) {
795 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
796 >                                         s & ~SUSPENDED))
797 >                return true;
798 >        }
799 >        return false;
800      }
801  
802      /**
803 <     * Sets suspended status and blocks as spare until resumed,
804 <     * shutdown, or timed out.
805 <     *
717 <     * @return false if trimmed
803 >     * Sets suspended status and blocks as spare until resumed
804 >     * or shutdown.
805 >     * @returns true if still running on exit
806       */
807      final boolean suspendAsSpare() {
808 <        for (;;) {               // set suspended unless terminating
808 >        lastEventCount = 0;         // reset upon resume
809 >        for (;;) {                  // set suspended unless terminating
810              int s = runState;
811              if ((s & TERMINATING) != 0) { // must kill
812                  if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
# Line 728 | Line 817 | public class ForkJoinWorkerThread extend
817                                                s | SUSPENDED))
818                  break;
819          }
731        lastEventCount = 0;      // reset upon resume
820          ForkJoinPool p = pool;
821 <        p.releaseWaiters();      // help others progress
734 <        p.accumulateStealCount(this);
735 <        interrupted();           // clear/ignore interrupts
736 <        if (poolIndex < p.getParallelism()) { // untimed wait
737 <            while ((runState & SUSPENDED) != 0)
738 <                doPark();
739 <            return true;
740 <        }
741 <        return timedSuspend();   // timed wait if apparently non-core
742 <    }
743 <
744 <    /**
745 <     * Blocks as spare until resumed or timed out
746 <     * @return false if trimmed
747 <     */
748 <    private boolean timedSuspend() {
749 <        long nanos = SPARE_KEEPALIVE_NANOS;
750 <        long startTime = System.nanoTime();
821 >        p.pushSpare(this);
822          while ((runState & SUSPENDED) != 0) {
823 <            ++parkCount;
824 <            if ((nanos -= (System.nanoTime() - startTime)) > 0)
825 <                LockSupport.parkNanos(this, nanos);
826 <            else { // try to trim on timeout
827 <                int s = runState;
828 <                if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
829 <                                             (s & ~SUSPENDED) |
830 <                                             (TRIMMED|TERMINATING)))
831 <                    return false;
823 >            if (!p.tryAccumulateStealCount(this))
824 >                continue;
825 >            interrupted();          // clear/ignore interrupts
826 >            if ((runState & SUSPENDED) == 0)
827 >                break;
828 >            if (nextSpare != 0)     // untimed
829 >                LockSupport.park(this);
830 >            else {
831 >                long startTime = System.nanoTime();
832 >                LockSupport.parkNanos(this, TRIM_RATE_NANOS);
833 >                if ((runState & SUSPENDED) == 0)
834 >                    break;
835 >                long now = System.nanoTime();
836 >                if (now - startTime >= TRIM_RATE_NANOS)
837 >                    pool.tryTrimSpare(now);
838              }
839          }
840 <        return true;
840 >        return runState == 0;
841      }
842  
843      // Misc support methods for ForkJoinPool
# Line 770 | Line 847 | public class ForkJoinWorkerThread extend
847       * used by ForkJoinTask.
848       */
849      final int getQueueSize() {
850 <        return -base + sp;
851 <    }
775 <
776 <    /**
777 <     * Set locallyFifo mode. Called only by ForkJoinPool
778 <     */
779 <    final void setAsyncMode(boolean async) {
780 <        locallyFifo = async;
850 >        int n; // external calls must read base first
851 >        return (n = -base + sp) <= 0 ? 0 : n;
852      }
853  
854      /**
# Line 785 | Line 856 | public class ForkJoinWorkerThread extend
856       * thread.
857       */
858      final void cancelTasks() {
859 +        ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
860 +        if (cj != null) {
861 +            currentJoin = null;
862 +            cj.cancelIgnoringExceptions();
863 +            try {
864 +                this.interrupt(); // awaken wait
865 +            } catch (SecurityException ignore) {
866 +            }
867 +        }
868 +        ForkJoinTask<?> cs = currentSteal;
869 +        if (cs != null) {
870 +            currentSteal = null;
871 +            cs.cancelIgnoringExceptions();
872 +        }
873          while (base != sp) {
874              ForkJoinTask<?> t = deqTask();
875              if (t != null)
# Line 812 | Line 897 | public class ForkJoinWorkerThread extend
897      // Support methods for ForkJoinTask
898  
899      /**
900 +     * Gets and removes a local task.
901 +     *
902 +     * @return a task, if available
903 +     */
904 +    final ForkJoinTask<?> pollLocalTask() {
905 +        while (sp != base) {
906 +            if (active || (active = pool.tryIncrementActiveCount()))
907 +                return locallyFifo? locallyDeqTask() : popTask();
908 +        }
909 +        return null;
910 +    }
911 +
912 +    /**
913 +     * Gets and removes a local or stolen task.
914 +     *
915 +     * @return a task, if available
916 +     */
917 +    final ForkJoinTask<?> pollTask() {
918 +        ForkJoinTask<?> t = pollLocalTask();
919 +        if (t == null) {
920 +            t = scan();
921 +            currentSteal = null; // cannot retain/track/help
922 +        }
923 +        return t;
924 +    }
925 +
926 +    /**
927 +     * Possibly runs some tasks and/or blocks, until task is done.
928 +     *
929 +     * @param joinMe the task to join
930 +     */
931 +    final void joinTask(ForkJoinTask<?> joinMe) {
932 +        // currentJoin only written by this thread; only need ordered store
933 +        ForkJoinTask<?> prevJoin = currentJoin;
934 +        UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe);
935 +        if (sp != base)
936 +            localHelpJoinTask(joinMe);
937 +        if (joinMe.status >= 0)
938 +            pool.awaitJoin(joinMe, this);
939 +        UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin);
940 +    }
941 +
942 +    /**
943 +     * Run tasks in local queue until given task is done.
944 +     *
945 +     * @param joinMe the task to join
946 +     */
947 +    private void localHelpJoinTask(ForkJoinTask<?> joinMe) {
948 +        int s;
949 +        ForkJoinTask<?>[] q;
950 +        while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) {
951 +            int i = (q.length - 1) & --s;
952 +            long u = (i << qShift) + qBase; // raw offset
953 +            ForkJoinTask<?> t = q[i];
954 +            if (t == null)  // lost to a stealer
955 +                break;
956 +            if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
957 +                /*
958 +                 * This recheck (and similarly in helpJoinTask)
959 +                 * handles cases where joinMe is independently
960 +                 * cancelled or forced even though there is other work
961 +                 * available. Back out of the pop by putting t back
962 +                 * into slot before we commit by writing sp.
963 +                 */
964 +                if (joinMe.status < 0) {
965 +                    UNSAFE.putObjectVolatile(q, u, t);
966 +                    break;
967 +                }
968 +                sp = s;
969 +                // UNSAFE.putOrderedInt(this, spOffset, s);
970 +                t.quietlyExec();
971 +            }
972 +        }
973 +    }
974 +
975 +    /**
976 +     * Tries to locate and help perform tasks for a stealer of the
977 +     * given task, or in turn one of its stealers.  Traces
978 +     * currentSteal->currentJoin links looking for a thread working on
979 +     * a descendant of the given task and with a non-empty queue to
980 +     * steal back and execute tasks from.
981 +     *
982 +     * The implementation is very branchy to cope with the potential
983 +     * inconsistencies or loops encountering chains that are stale,
984 +     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
985 +     * of these cases are dealt with by just returning back to the
986 +     * caller, who is expected to retry if other join mechanisms also
987 +     * don't work out.
988 +     *
989 +     * @param joinMe the task to join
990 +     */
991 +    final void helpJoinTask(ForkJoinTask<?> joinMe) {
992 +        ForkJoinWorkerThread[] ws = pool.workers;
993 +        int n; // need at least 2 workers
994 +        if (ws != null && (n = ws.length) > 1 && joinMe.status >= 0) {
995 +            ForkJoinTask<?> task = joinMe;        // base of chain
996 +            ForkJoinWorkerThread thread = this;   // thread with stolen task
997 +            for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length
998 +                // Try to find v, the stealer of task, by first using hint
999 +                ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)];
1000 +                if (v == null || v.currentSteal != task) {
1001 +                    for (int j = 0; ; ++j) {      // search array
1002 +                        if (j < n) {
1003 +                            if ((v = ws[j]) != null) {
1004 +                                if (task.status < 0)
1005 +                                    return;       // stale or done
1006 +                                if (v.currentSteal == task) {
1007 +                                    thread.stealHint = j;
1008 +                                    break;        // save hint for next time
1009 +                                }
1010 +                            }
1011 +                        }
1012 +                        else
1013 +                            return;               // no stealer
1014 +                    }
1015 +                }
1016 +                // Try to help v, using specialized form of deqTask
1017 +                int b;
1018 +                ForkJoinTask<?>[] q;
1019 +                while ((b = v.base) != v.sp && (q = v.queue) != null) {
1020 +                    int i = (q.length - 1) & b;
1021 +                    long u = (i << qShift) + qBase;
1022 +                    ForkJoinTask<?> t = q[i];
1023 +                    if (task.status < 0)
1024 +                        return;                   // stale or done
1025 +                    if (v.base == b) {
1026 +                        if (t == null)
1027 +                            return;               // producer stalled
1028 +                        if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
1029 +                            if (joinMe.status < 0) {
1030 +                                UNSAFE.putObjectVolatile(q, u, t);
1031 +                                return;           // back out on cancel
1032 +                            }
1033 +                            int pid = poolIndex;
1034 +                            ForkJoinTask<?> prevSteal = currentSteal;
1035 +                            currentSteal = t;
1036 +                            v.stealHint = pid;
1037 +                            v.base = b + 1;
1038 +                            t.quietlyExec();
1039 +                            currentSteal = prevSteal;
1040 +                        }
1041 +                    }
1042 +                    if (joinMe.status < 0)
1043 +                        return;
1044 +                }
1045 +                // Try to descend to find v's stealer
1046 +                ForkJoinTask<?> next = v.currentJoin;
1047 +                if (task.status < 0 || next == null || next == task ||
1048 +                    joinMe.status < 0)
1049 +                    return;
1050 +                task = next;
1051 +                thread = v;
1052 +            }
1053 +        }
1054 +    }
1055 +
1056 +    /**
1057       * Returns an estimate of the number of tasks, offset by a
1058       * function of number of idle workers.
1059       *
# Line 863 | Line 1105 | public class ForkJoinWorkerThread extend
1105      }
1106  
1107      /**
866     * Gets and removes a local task.
867     *
868     * @return a task, if available
869     */
870    final ForkJoinTask<?> pollLocalTask() {
871        while (base != sp) {
872            if (active || (active = pool.tryIncrementActiveCount()))
873                return locallyFifo? locallyDeqTask() : popTask();
874        }
875        return null;
876    }
877
878    /**
879     * Gets and removes a local or stolen task.
880     *
881     * @return a task, if available
882     */
883    final ForkJoinTask<?> pollTask() {
884        ForkJoinTask<?> t;
885        return (t = pollLocalTask()) != null ? t : scan();
886    }
887
888    /**
889     * Executes or processes other tasks awaiting the given task
890     * @return task completion status
891     */
892    final int execWhileJoining(ForkJoinTask<?> joinMe) {
893        int s;
894        while ((s = joinMe.status) >= 0) {
895            ForkJoinTask<?> t = base != sp?
896                popWhileJoining(joinMe) :
897                scanWhileJoining(joinMe);
898            if (t != null)
899                t.tryExec();
900        }
901        return s;
902    }
903
904    /**
905     * Returns or stolen task, if available, unless joinMe is done
906     *
907     * This method is intrinsically nonmodular. To maintain the
908     * property that tasks are never stolen if the awaited task is
909     * ready, we must interleave mechanics of scan with status
910     * checks. We rely here on the commit points of deq that allow us
911     * to cancel a steal even after CASing slot to null, but before
912     * adjusting base index: If, after the CAS, we see that joinMe is
913     * ready, we can back out by placing the task back into the slot,
914     * without adjusting index. The loop is otherwise a variant of the
915     * one in scan().
916     *
917     */
918    private ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
919        int r = seed;
920        ForkJoinPool p = pool;
921        ForkJoinWorkerThread[] ws;
922        int n;
923        outer:while ((ws = p.workers) != null && (n = ws.length) > 1) {
924            int mask = n - 1;
925            int k = r;
926            boolean contended = false; // to retry loop if deq contends
927            for (int j = -n; j <= n; ++j) {
928                if (joinMe.status < 0)
929                    break outer;
930                int b;
931                ForkJoinTask<?>[] q;
932                ForkJoinWorkerThread v = ws[k & mask];
933                r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
934                if (v != null && (b=v.base) != v.sp && (q=v.queue) != null) {
935                    int i = (q.length - 1) & b;
936                    ForkJoinTask<?> t = q[i];
937                    if (t != null && UNSAFE.compareAndSwapObject
938                        (q, (i << qShift) + qBase, t, null)) {
939                        if (joinMe.status >= 0) {
940                            v.base = b + 1;
941                            seed = r;
942                            ++stealCount;
943                            return t;
944                        }
945                        UNSAFE.putObjectVolatile(q, (i<<qShift)+qBase, t);
946                        break outer; // back out
947                    }
948                    contended = true;
949                }
950                k = j < 0 ? r : (k + ((n >>> 1) | 1));
951            }
952            if (!contended && p.tryAwaitBusyJoin(joinMe))
953                break;
954        }
955        return null;
956    }
957
958    /**
959     * Version of popTask with join checks surrounding extraction.
960     * Uses the same backout strategy as helpJoinTask. Note that
961     * we ignore locallyFifo flag for local tasks here since helping
962     * joins only make sense in LIFO mode.
963     *
964     * @return a popped task, if available, unless joinMe is done
965     */
966    private ForkJoinTask<?> popWhileJoining(ForkJoinTask<?> joinMe) {
967        int s;
968        ForkJoinTask<?>[] q;
969        while ((s = sp) != base && (q = queue) != null && joinMe.status >= 0) {
970            int i = (q.length - 1) & --s;
971            ForkJoinTask<?> t = q[i];
972            if (t != null && UNSAFE.compareAndSwapObject
973                (q, (i << qShift) + qBase, t, null)) {
974                if (joinMe.status >= 0) {
975                    sp = s;
976                    return t;
977                }
978                UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t);
979                break;  // back out
980            }
981        }
982        return null;
983    }
984
985    /**
1108       * Runs tasks until {@code pool.isQuiescent()}.
1109       */
1110      final void helpQuiescePool() {
1111          for (;;) {
1112              ForkJoinTask<?> t = pollLocalTask();
1113 <            if (t != null || (t = scan()) != null)
1114 <                t.tryExec();
1113 >            if (t != null || (t = scan()) != null) {
1114 >                t.quietlyExec();
1115 >                currentSteal = null;
1116 >            }
1117              else {
1118                  ForkJoinPool p = pool;
1119                  if (active) {
1120 +                    if (!p.tryDecrementActiveCount())
1121 +                        continue;   // retry later
1122                      active = false; // inactivate
997                    do {} while (!p.tryDecrementActiveCount());
1123                  }
1124                  if (p.isQuiescent()) {
1125                      active = true; // re-activate
# Line 1008 | Line 1133 | public class ForkJoinWorkerThread extend
1133      // Unsafe mechanics
1134  
1135      private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1136 +    private static final long spOffset =
1137 +        objectFieldOffset("sp", ForkJoinWorkerThread.class);
1138      private static final long runStateOffset =
1139          objectFieldOffset("runState", ForkJoinWorkerThread.class);
1140 +    private static final long currentJoinOffset =
1141 +        objectFieldOffset("currentJoin", ForkJoinWorkerThread.class);
1142 +    private static final long currentStealOffset =
1143 +        objectFieldOffset("currentSteal", ForkJoinWorkerThread.class);
1144      private static final long qBase =
1145          UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
1146 +
1147      private static final int qShift;
1148  
1149      static {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines