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.34 by dl, Fri Jun 4 14:37:54 2010 UTC vs.
Revision 1.41 by dl, Tue Aug 17 18:30:33 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 oldest 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 =
172 <        5L * 1000L * 1000L * 1000L; // 5 secs
171 >    private static final long TRIM_RATE_NANOS =
172 >        5L * 1000L * 1000L * 1000L; // 5sec
173  
174      /**
175       * Capacity of work-stealing queue array upon initialization.
# Line 178 | Line 213 | public class ForkJoinWorkerThread extend
213      private int sp;
214  
215      /**
216 +     * The index of most recent stealer, used as a hint to avoid
217 +     * traversal in method helpJoinTask. This is only a hint because a
218 +     * worker might have had multiple steals and this only holds one
219 +     * of them (usually the most current). Declared non-volatile,
220 +     * relying on other prevailing sync to keep reasonably current.
221 +     */
222 +    private int stealHint;
223 +
224 +    /**
225       * Run state of this worker. In addition to the usual run levels,
226       * tracks if this worker is suspended as a spare, and if it was
227       * killed (trimmed) while suspended. However, "active" status is
228 <     * maintained separately.
228 >     * maintained separately and modified only in conjunction with
229 >     * CASes of the pool's runState (which are currently sadly manually
230 >     * inlined for performance.)
231       */
232      private volatile int runState;
233  
# Line 191 | Line 237 | public class ForkJoinWorkerThread extend
237      private static final int TRIMMED     = 0x08; // killed while suspended
238  
239      /**
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    /**
240       * Number of steals, transferred and reset in pool callbacks pool
241       * when idle Accessed directly by pool.
242       */
# Line 218 | Line 256 | public class ForkJoinWorkerThread extend
256  
257      /**
258       * True if use local fifo, not default lifo, for local polling.
259 <     * Shadows value from ForkJoinPool, which resets it if changed
222 <     * pool-wide.
259 >     * Shadows value from ForkJoinPool.
260       */
261 <    private boolean locallyFifo;
261 >    private final boolean locallyFifo;
262  
263      /**
264       * Index of this worker in pool array. Set once by pool before
# Line 243 | Line 280 | public class ForkJoinWorkerThread extend
280      volatile long nextWaiter;
281  
282      /**
283 +     * Number of times this thread suspended as spare
284 +     */
285 +    int spareCount;
286 +
287 +    /**
288 +     * Encoded index and count of next spare waiter. Used only
289 +     * by ForkJoinPool for managing spares.
290 +     */
291 +    volatile int nextSpare;
292 +
293 +    /**
294 +     * The task currently being joined, set only when actively trying
295 +     * to helpStealer. Written only by current thread, but read by
296 +     * others.
297 +     */
298 +    private volatile ForkJoinTask<?> currentJoin;
299 +
300 +    /**
301 +     * The task most recently stolen from another worker (or
302 +     * submission queue).  Not volatile because always read/written in
303 +     * presence of related volatiles in those cases where it matters.
304 +     */
305 +    private ForkJoinTask<?> currentSteal;
306 +
307 +    /**
308       * Creates a ForkJoinWorkerThread operating in the given pool.
309       *
310       * @param pool the pool this thread works in
311       * @throws NullPointerException if pool is null
312       */
313      protected ForkJoinWorkerThread(ForkJoinPool pool) {
252        if (pool == null) throw new NullPointerException();
314          this.pool = pool;
315 +        this.locallyFifo = pool.locallyFifo;
316 +        setDaemon(true);
317          // To avoid exposing construction details to subclasses,
318          // remaining initialization is in start() and onStart()
319      }
# Line 258 | Line 321 | public class ForkJoinWorkerThread extend
321      /**
322       * Performs additional initialization and starts this thread
323       */
324 <    final void start(int poolIndex, boolean locallyFifo,
262 <                     UncaughtExceptionHandler ueh) {
324 >    final void start(int poolIndex, UncaughtExceptionHandler ueh) {
325          this.poolIndex = poolIndex;
264        this.locallyFifo = locallyFifo;
326          if (ueh != null)
327              setUncaughtExceptionHandler(ueh);
267        setDaemon(true);
328          start();
329      }
330  
# Line 305 | Line 365 | public class ForkJoinWorkerThread extend
365          int rs = seedGenerator.nextInt();
366          seed = rs == 0? 1 : rs; // seed must be nonzero
367  
368 <        // Allocate name string and queue array in this thread
368 >        // Allocate name string and arrays in this thread
369          String pid = Integer.toString(pool.getPoolNumber());
370          String wid = Integer.toString(poolIndex);
371          setName("ForkJoinPool-" + pid + "-worker-" + wid);
# Line 323 | Line 383 | public class ForkJoinWorkerThread extend
383       */
384      protected void onTermination(Throwable exception) {
385          try {
386 +            ForkJoinPool p = pool;
387 +            if (active) {
388 +                int a; // inline p.tryDecrementActiveCount
389 +                active = false;
390 +                do {} while(!UNSAFE.compareAndSwapInt
391 +                            (p, poolRunStateOffset, a = p.runState, a - 1));
392 +            }
393              cancelTasks();
394              setTerminated();
395 <            pool.workerTerminated(this);
395 >            p.workerTerminated(this);
396          } catch (Throwable ex) {        // Shouldn't ever happen
397              if (exception == null)      // but if so, at least rethrown
398                  exception = ex;
# Line 358 | Line 425 | public class ForkJoinWorkerThread extend
425       * Find and execute tasks and check status while running
426       */
427      private void mainLoop() {
428 <        boolean ran = false;      // true if ran task in last loop iter
362 <        boolean prevRan = false;  // true if ran on last or previous step
428 >        int misses = 0; // track consecutive times failed to find work; max 2
429          ForkJoinPool p = pool;
430          for (;;) {
431 <            p.preStep(this, prevRan);
431 >            p.preStep(this, misses);
432              if (runState != 0)
433 <                return;
434 <            ForkJoinTask<?> t; // try to get and run stolen or submitted task
435 <            if ((t = scan()) != null || (t = pollSubmission()) != null) {
370 <                t.tryExec();
371 <                if (base != sp)
372 <                    runLocalTasks();
373 <                prevRan = ran = true;
374 <            }
375 <            else {
376 <                prevRan = ran;
377 <                ran = false;
378 <            }
433 >                break;
434 >            misses = ((tryExecSteal() || tryExecSubmission()) ? 0 :
435 >                      (misses < 2 ? misses + 1 : 2));
436          }
437      }
438  
439      /**
440 <     * Runs local tasks until queue is empty or shut down.  Call only
441 <     * while active.
440 >     * Try to steal a task and execute it
441 >     *
442 >     * @return true if ran a task
443       */
444 <    private void runLocalTasks() {
445 <        while (runState == 0) {
446 <            ForkJoinTask<?> t = locallyFifo? locallyDeqTask() : popTask();
447 <            if (t != null)
448 <                t.tryExec();
449 <            else if (base == sp)
450 <                break;
444 >    private boolean tryExecSteal() {
445 >        ForkJoinTask<?> t;
446 >        if ((t  = scan()) != null) {
447 >            t.quietlyExec();
448 >            currentSteal = null;
449 >            if (sp != base)
450 >                execLocalTasks();
451 >            return true;
452          }
453 +        return false;
454      }
455  
456      /**
457 <     * If a submission exists, try to activate and take it
457 >     * If a submission exists, try to activate and run it;
458       *
459 <     * @return a task, if available
459 >     * @return true if ran a task
460       */
461 <    private ForkJoinTask<?> pollSubmission() {
461 >    private boolean tryExecSubmission() {
462          ForkJoinPool p = pool;
463          while (p.hasQueuedSubmissions()) {
464 <            if (active || (active = p.tryIncrementActiveCount())) {
465 <                ForkJoinTask<?> t = p.pollSubmission();
466 <                return t != null ? t : scan(); // if missed, rescan
464 >            ForkJoinTask<?> t; int a;
465 >            if (active || // ugly/hacky: inline p.tryIncrementActiveCount
466 >                (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
467 >                                                   a = p.runState, a + 1))) {
468 >                if ((t = p.pollSubmission()) != null) {
469 >                    currentSteal = t;
470 >                    t.quietlyExec();
471 >                    currentSteal = null;
472 >                    if (sp != base)
473 >                        execLocalTasks();
474 >                    return true;
475 >                }
476              }
477          }
478 <        return null;
478 >        return false;
479 >    }
480 >
481 >    /**
482 >     * Runs local tasks until queue is empty or shut down.  Call only
483 >     * while active.
484 >     */
485 >    private void execLocalTasks() {
486 >        while (runState == 0) {
487 >            ForkJoinTask<?> t = locallyFifo? locallyDeqTask() : popTask();
488 >            if (t != null)
489 >                t.quietlyExec();
490 >            else if (sp == base)
491 >                break;
492 >        }
493      }
494  
495      /*
# Line 466 | Line 549 | public class ForkJoinWorkerThread extend
549      /**
550       * Tries to take a task from the base of the queue, failing if
551       * empty or contended. Note: Specializations of this code appear
552 <     * in scan and scanWhileJoining.
552 >     * in locallyDeqTask and elsewhere.
553       *
554       * @return a task, or null if none or contended
555       */
# Line 474 | Line 557 | public class ForkJoinWorkerThread extend
557          ForkJoinTask<?> t;
558          ForkJoinTask<?>[] q;
559          int b, i;
560 <        if ((b = base) != sp &&
560 >        if (sp != (b = base) &&
561              (q = queue) != null && // must read q after b
562 <            (t = q[i = (q.length - 1) & b]) != null &&
562 >            (t = q[i = (q.length - 1) & b]) != null && base == b &&
563              UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase, t, null)) {
564              base = b + 1;
565              return t;
# Line 496 | Line 579 | public class ForkJoinWorkerThread extend
579              ForkJoinTask<?> t;
580              int b, i;
581              while (sp != (b = base)) {
582 <                if ((t = q[i = (q.length - 1) & b]) != null &&
582 >                if ((t = q[i = (q.length - 1) & b]) != null && base == b &&
583                      UNSAFE.compareAndSwapObject(q, (i << qShift) + qBase,
584                                                  t, null)) {
585                      base = b + 1;
# Line 509 | Line 592 | public class ForkJoinWorkerThread extend
592  
593      /**
594       * Returns a popped task, or null if empty. Assumes active status.
595 <     * Called only by current thread. (Note: a specialization of this
513 <     * code appears in popWhileJoining.)
595 >     * Called only by current thread.
596       */
597 <    final ForkJoinTask<?> popTask() {
598 <        int s;
599 <        ForkJoinTask<?>[] q;
600 <        if (base != (s = sp) && (q = queue) != null) {
601 <            int i = (q.length - 1) & --s;
602 <            ForkJoinTask<?> t = q[i];
603 <            if (t != null && UNSAFE.compareAndSwapObject
604 <                (q, (i << qShift) + qBase, t, null)) {
605 <                sp = s;
606 <                return t;
597 >    private ForkJoinTask<?> popTask() {
598 >        ForkJoinTask<?>[] q = queue;
599 >        if (q != null) {
600 >            int s;
601 >            while ((s = sp) != base) {
602 >                int i = (q.length - 1) & --s;
603 >                long u = (i << qShift) + qBase; // raw offset
604 >                ForkJoinTask<?> t = q[i];
605 >                if (t == null)   // lost to stealer
606 >                    break;
607 >                if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
608 >                    sp = s; // putOrderedInt may encourage more timely write
609 >                    // UNSAFE.putOrderedInt(this, spOffset, s);
610 >                    return t;
611 >                }
612              }
613          }
614          return null;
# Line 536 | Line 623 | public class ForkJoinWorkerThread extend
623       */
624      final boolean unpushTask(ForkJoinTask<?> t) {
625          int s;
626 <        ForkJoinTask<?>[] q;
627 <        if (base != (s = sp) && (q = queue) != null &&
626 >        ForkJoinTask<?>[] q = queue;
627 >        if ((s = sp) != base && q != null &&
628              UNSAFE.compareAndSwapObject
629              (q, (((q.length - 1) & --s) << qShift) + qBase, t, null)) {
630              sp = s;
631 +            // UNSAFE.putOrderedInt(this, spOffset, s);
632              return true;
633          }
634          return false;
# Line 629 | Line 717 | public class ForkJoinWorkerThread extend
717                  ForkJoinWorkerThread v = ws[k & mask];
718                  r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // inline xorshift
719                  if (v != null && v.base != v.sp) {
720 <                    int b, i;             // inline specialized deqTask
721 <                    ForkJoinTask<?>[] q;
722 <                    ForkJoinTask<?> t;
723 <                    if ((canSteal ||      // ensure active status
724 <                         (canSteal = active = p.tryIncrementActiveCount())) &&
725 <                        (q = v.queue) != null &&
726 <                        (t = q[i = (q.length - 1) & (b = v.base)]) != null &&
727 <                        UNSAFE.compareAndSwapObject
728 <                        (q, (i << qShift) + qBase, t, null)) {
729 <                        v.base = b + 1;
730 <                        seed = r;
731 <                        ++stealCount;
732 <                        return t;
720 >                    ForkJoinTask<?>[] q; int b, a;
721 >                    if ((canSteal ||      // Ugly/hacky: inline
722 >                         (canSteal = active =  // p.tryIncrementActiveCount
723 >                          UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
724 >                                                   a = p.runState, a + 1))) &&
725 >                        (q = v.queue) != null && (b = v.base) != v.sp) {
726 >                        int i = (q.length - 1) & b;
727 >                        long u = (i << qShift) + qBase; // raw offset
728 >                        ForkJoinTask<?> t = q[i];
729 >                        if (v.base == b && t != null &&
730 >                            UNSAFE.compareAndSwapObject(q, u, t, null)) {
731 >                            int pid = poolIndex;
732 >                            currentSteal = t;
733 >                            v.stealHint = pid;
734 >                            v.base = b + 1;
735 >                            seed = r;
736 >                            ++stealCount;
737 >                            return t;
738 >                        }
739                      }
740                      j = -n;
741                      k = r;                // restart on contention
# Line 660 | Line 754 | public class ForkJoinWorkerThread extend
754      // Run State management
755  
756      // status check methods used mainly by ForkJoinPool
757 +    final boolean isRunning()     { return runState == 0; }
758      final boolean isTerminating() { return (runState & TERMINATING) != 0; }
759      final boolean isTerminated()  { return (runState & TERMINATED) != 0; }
760      final boolean isSuspended()   { return (runState & SUSPENDED) != 0; }
761      final boolean isTrimmed()     { return (runState & TRIMMED) != 0; }
762  
763      /**
764 <     * Sets state to TERMINATING, also resuming if suspended.
764 >     * Sets state to TERMINATING. Does NOT unpark or interrupt
765 >     * to wake up if currently blocked.
766       */
767      final void shutdown() {
768          for (;;) {
769              int s = runState;
770 +            if ((s & (TERMINATING|TERMINATED)) != 0)
771 +                break;
772              if ((s & SUSPENDED) != 0) { // kill and wakeup if suspended
773                  if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
774                                               (s & ~SUSPENDED) |
775 <                                             (TRIMMED|TERMINATING))) {
678 <                    LockSupport.unpark(this);
775 >                                             (TRIMMED|TERMINATING)))
776                      break;
680                }
777              }
778              else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
779                                                s | TERMINATING))
# Line 686 | Line 782 | public class ForkJoinWorkerThread extend
782      }
783  
784      /**
785 <     * Sets state to TERMINATED. Called only by this thread.
785 >     * Sets state to TERMINATED. Called only by onTermination()
786       */
787      private void setTerminated() {
788          int s;
# Line 696 | Line 792 | public class ForkJoinWorkerThread extend
792      }
793  
794      /**
699     * Instrumented version of park. Also used by ForkJoinPool.awaitEvent
700     */
701    final void doPark() {
702        ++parkCount;
703        LockSupport.park(this);
704    }
705
706    /**
795       * If suspended, tries to set status to unsuspended.
708     * Caller must unpark to actually resume
796       *
797       * @return true if successful
798       */
799      final boolean tryUnsuspend() {
800          int s;
801 <        return (((s = runState) & SUSPENDED) != 0 &&
802 <                UNSAFE.compareAndSwapInt(this, runStateOffset, s,
803 <                                         s & ~SUSPENDED));
801 >        while (((s = runState) & SUSPENDED) != 0) {
802 >            if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
803 >                                         s & ~SUSPENDED))
804 >                return true;
805 >        }
806 >        return false;
807      }
808  
809      /**
810 <     * Sets suspended status and blocks as spare until resumed,
811 <     * shutdown, or timed out.
722 <     *
723 <     * @return false if trimmed
810 >     * Sets suspended status and blocks as spare until resumed
811 >     * or shutdown.
812       */
813 <    final boolean suspendAsSpare() {
814 <        for (;;) {               // set suspended unless terminating
813 >    final void suspendAsSpare() {
814 >        for (;;) {                  // set suspended unless terminating
815              int s = runState;
816              if ((s & TERMINATING) != 0) { // must kill
817                  if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
818                                               s | (TRIMMED | TERMINATING)))
819 <                    return false;
819 >                    return;
820              }
821              else if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
822                                                s | SUSPENDED))
823                  break;
824          }
737        lastEventCount = 0;      // reset upon resume
825          ForkJoinPool p = pool;
826 <        p.releaseWaiters();      // help others progress
827 <        p.accumulateStealCount(this);
741 <        interrupted();           // clear/ignore interrupts
742 <        if (poolIndex < p.getParallelism()) { // untimed wait
743 <            while ((runState & SUSPENDED) != 0)
744 <                doPark();
745 <            return true;
746 <        }
747 <        return timedSuspend();   // timed wait if apparently non-core
748 <    }
749 <
750 <    /**
751 <     * Blocks as spare until resumed or timed out
752 <     * @return false if trimmed
753 <     */
754 <    private boolean timedSuspend() {
755 <        long nanos = SPARE_KEEPALIVE_NANOS;
756 <        long startTime = System.nanoTime();
826 >        p.pushSpare(this);
827 >        lastEventCount = 0;         // reset upon resume
828          while ((runState & SUSPENDED) != 0) {
829 <            ++parkCount;
830 <            if ((nanos -= (System.nanoTime() - startTime)) > 0)
831 <                LockSupport.parkNanos(this, nanos);
832 <            else { // try to trim on timeout
833 <                int s = runState;
834 <                if (UNSAFE.compareAndSwapInt(this, runStateOffset, s,
835 <                                             (s & ~SUSPENDED) |
836 <                                             (TRIMMED|TERMINATING)))
837 <                    return false;
829 >            if (p.tryAccumulateStealCount(this)) {
830 >                boolean untimed = nextSpare != 0;
831 >                long startTime = untimed? 0 : System.nanoTime();
832 >                interrupted();          // clear/ignore interrupts
833 >                if ((runState & SUSPENDED) == 0)
834 >                    break;
835 >                if (untimed)     // untimed
836 >                    LockSupport.park(this);
837 >                else {
838 >                    LockSupport.parkNanos(this, TRIM_RATE_NANOS);
839 >                    if ((runState & SUSPENDED) == 0)
840 >                        break;
841 >                    if (System.nanoTime() - startTime >= TRIM_RATE_NANOS)
842 >                        p.tryShutdownSpare();
843 >                }
844              }
845          }
769        return true;
846      }
847  
848      // Misc support methods for ForkJoinPool
# Line 776 | Line 852 | public class ForkJoinWorkerThread extend
852       * used by ForkJoinTask.
853       */
854      final int getQueueSize() {
855 <        return -base + sp;
856 <    }
781 <
782 <    /**
783 <     * Set locallyFifo mode. Called only by ForkJoinPool
784 <     */
785 <    final void setAsyncMode(boolean async) {
786 <        locallyFifo = async;
855 >        int n; // external calls must read base first
856 >        return (n = -base + sp) <= 0 ? 0 : n;
857      }
858  
859      /**
# Line 791 | Line 861 | public class ForkJoinWorkerThread extend
861       * thread.
862       */
863      final void cancelTasks() {
864 +        ForkJoinTask<?> cj = currentJoin; // try to cancel ongoing tasks
865 +        if (cj != null) {
866 +            currentJoin = null;
867 +            cj.cancelIgnoringExceptions();
868 +            try {
869 +                this.interrupt(); // awaken wait
870 +            } catch (SecurityException ignore) {
871 +            }
872 +        }
873 +        ForkJoinTask<?> cs = currentSteal;
874 +        if (cs != null) {
875 +            currentSteal = null;
876 +            cs.cancelIgnoringExceptions();
877 +        }
878          while (base != sp) {
879              ForkJoinTask<?> t = deqTask();
880              if (t != null)
# Line 818 | Line 902 | public class ForkJoinWorkerThread extend
902      // Support methods for ForkJoinTask
903  
904      /**
905 +     * Gets and removes a local task.
906 +     *
907 +     * @return a task, if available
908 +     */
909 +    final ForkJoinTask<?> pollLocalTask() {
910 +        ForkJoinPool p = pool;
911 +        while (sp != base) {
912 +            int a; // inline p.tryIncrementActiveCount
913 +            if (active ||
914 +                (active = UNSAFE.compareAndSwapInt(p, poolRunStateOffset,
915 +                                                   a = p.runState, a + 1)))
916 +                return locallyFifo? locallyDeqTask() : popTask();
917 +        }
918 +        return null;
919 +    }
920 +
921 +    /**
922 +     * Gets and removes a local or stolen task.
923 +     *
924 +     * @return a task, if available
925 +     */
926 +    final ForkJoinTask<?> pollTask() {
927 +        ForkJoinTask<?> t = pollLocalTask();
928 +        if (t == null) {
929 +            t = scan();
930 +            currentSteal = null; // cannot retain/track/help
931 +        }
932 +        return t;
933 +    }
934 +
935 +    /**
936 +     * Possibly runs some tasks and/or blocks, until task is done.
937 +     *
938 +     * @param joinMe the task to join
939 +     */
940 +    final void joinTask(ForkJoinTask<?> joinMe) {
941 +        // currentJoin only written by this thread; only need ordered store
942 +        ForkJoinTask<?> prevJoin = currentJoin;
943 +        UNSAFE.putOrderedObject(this, currentJoinOffset, joinMe);
944 +        if (sp != base)
945 +            localHelpJoinTask(joinMe);
946 +        if (joinMe.status >= 0)
947 +            pool.awaitJoin(joinMe, this);
948 +        UNSAFE.putOrderedObject(this, currentJoinOffset, prevJoin);
949 +    }
950 +
951 +    /**
952 +     * Run tasks in local queue until given task is done.
953 +     *
954 +     * @param joinMe the task to join
955 +     */
956 +    private void localHelpJoinTask(ForkJoinTask<?> joinMe) {
957 +        int s;
958 +        ForkJoinTask<?>[] q;
959 +        while (joinMe.status >= 0 && (s = sp) != base && (q = queue) != null) {
960 +            int i = (q.length - 1) & --s;
961 +            long u = (i << qShift) + qBase; // raw offset
962 +            ForkJoinTask<?> t = q[i];
963 +            if (t == null)  // lost to a stealer
964 +                break;
965 +            if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
966 +                /*
967 +                 * This recheck (and similarly in helpJoinTask)
968 +                 * handles cases where joinMe is independently
969 +                 * cancelled or forced even though there is other work
970 +                 * available. Back out of the pop by putting t back
971 +                 * into slot before we commit by writing sp.
972 +                 */
973 +                if (joinMe.status < 0) {
974 +                    UNSAFE.putObjectVolatile(q, u, t);
975 +                    break;
976 +                }
977 +                sp = s;
978 +                // UNSAFE.putOrderedInt(this, spOffset, s);
979 +                t.quietlyExec();
980 +            }
981 +        }
982 +    }
983 +
984 +    /**
985 +     * Tries to locate and help perform tasks for a stealer of the
986 +     * given task, or in turn one of its stealers.  Traces
987 +     * currentSteal->currentJoin links looking for a thread working on
988 +     * a descendant of the given task and with a non-empty queue to
989 +     * steal back and execute tasks from.
990 +     *
991 +     * The implementation is very branchy to cope with the potential
992 +     * inconsistencies or loops encountering chains that are stale,
993 +     * unknown, or of length greater than MAX_HELP_DEPTH links.  All
994 +     * of these cases are dealt with by just returning back to the
995 +     * caller, who is expected to retry if other join mechanisms also
996 +     * don't work out.
997 +     *
998 +     * @param joinMe the task to join
999 +     */
1000 +    final void helpJoinTask(ForkJoinTask<?> joinMe) {
1001 +        ForkJoinWorkerThread[] ws = pool.workers;
1002 +        int n; // need at least 2 workers
1003 +        if (ws != null && (n = ws.length) > 1 && joinMe.status >= 0) {
1004 +            ForkJoinTask<?> task = joinMe;        // base of chain
1005 +            ForkJoinWorkerThread thread = this;   // thread with stolen task
1006 +            for (int d = 0; d < MAX_HELP_DEPTH; ++d) { // chain length
1007 +                // Try to find v, the stealer of task, by first using hint
1008 +                ForkJoinWorkerThread v = ws[thread.stealHint & (n - 1)];
1009 +                if (v == null || v.currentSteal != task) {
1010 +                    for (int j = 0; ; ++j) {      // search array
1011 +                        if (j < n) {
1012 +                            if ((v = ws[j]) != null) {
1013 +                                if (task.status < 0)
1014 +                                    return;       // stale or done
1015 +                                if (v.currentSteal == task) {
1016 +                                    thread.stealHint = j;
1017 +                                    break;        // save hint for next time
1018 +                                }
1019 +                            }
1020 +                        }
1021 +                        else
1022 +                            return;               // no stealer
1023 +                    }
1024 +                }
1025 +                // Try to help v, using specialized form of deqTask
1026 +                int b;
1027 +                ForkJoinTask<?>[] q;
1028 +                while ((b = v.base) != v.sp && (q = v.queue) != null) {
1029 +                    int i = (q.length - 1) & b;
1030 +                    long u = (i << qShift) + qBase;
1031 +                    ForkJoinTask<?> t = q[i];
1032 +                    if (task.status < 0)
1033 +                        return;                   // stale or done
1034 +                    if (v.base == b) {
1035 +                        if (t == null)
1036 +                            return;               // producer stalled
1037 +                        if (UNSAFE.compareAndSwapObject(q, u, t, null)) {
1038 +                            if (joinMe.status < 0) {
1039 +                                UNSAFE.putObjectVolatile(q, u, t);
1040 +                                return;           // back out on cancel
1041 +                            }
1042 +                            int pid = poolIndex;
1043 +                            ForkJoinTask<?> prevSteal = currentSteal;
1044 +                            currentSteal = t;
1045 +                            v.stealHint = pid;
1046 +                            v.base = b + 1;
1047 +                            t.quietlyExec();
1048 +                            currentSteal = prevSteal;
1049 +                        }
1050 +                    }
1051 +                    if (joinMe.status < 0)
1052 +                        return;
1053 +                }
1054 +                // Try to descend to find v's stealer
1055 +                ForkJoinTask<?> next = v.currentJoin;
1056 +                if (task.status < 0 || next == null || next == task ||
1057 +                    joinMe.status < 0)
1058 +                    return;
1059 +                task = next;
1060 +                thread = v;
1061 +            }
1062 +        }
1063 +    }
1064 +
1065 +    /**
1066       * Returns an estimate of the number of tasks, offset by a
1067       * function of number of idle workers.
1068       *
# Line 869 | Line 1114 | public class ForkJoinWorkerThread extend
1114      }
1115  
1116      /**
872     * Gets and removes a local task.
873     *
874     * @return a task, if available
875     */
876    final ForkJoinTask<?> pollLocalTask() {
877        while (base != sp) {
878            if (active || (active = pool.tryIncrementActiveCount()))
879                return locallyFifo? locallyDeqTask() : popTask();
880        }
881        return null;
882    }
883
884    /**
885     * Gets and removes a local or stolen task.
886     *
887     * @return a task, if available
888     */
889    final ForkJoinTask<?> pollTask() {
890        ForkJoinTask<?> t;
891        return (t = pollLocalTask()) != null ? t : scan();
892    }
893
894    /**
895     * Executes or processes other tasks awaiting the given task
896     * @return task completion status
897     */
898    final int execWhileJoining(ForkJoinTask<?> joinMe) {
899        int s;
900        while ((s = joinMe.status) >= 0) {
901            ForkJoinTask<?> t = base != sp?
902                popWhileJoining(joinMe) :
903                scanWhileJoining(joinMe);
904            if (t != null)
905                t.tryExec();
906        }
907        return s;
908    }
909
910    /**
911     * Returns or stolen task, if available, unless joinMe is done
912     *
913     * This method is intrinsically nonmodular. To maintain the
914     * property that tasks are never stolen if the awaited task is
915     * ready, we must interleave mechanics of scan with status
916     * checks. We rely here on the commit points of deq that allow us
917     * to cancel a steal even after CASing slot to null, but before
918     * adjusting base index: If, after the CAS, we see that joinMe is
919     * ready, we can back out by placing the task back into the slot,
920     * without adjusting index. The loop is otherwise a variant of the
921     * one in scan().
922     *
923     */
924    private ForkJoinTask<?> scanWhileJoining(ForkJoinTask<?> joinMe) {
925        int r = seed;
926        ForkJoinPool p = pool;
927        ForkJoinWorkerThread[] ws;
928        int n;
929        outer:while ((ws = p.workers) != null && (n = ws.length) > 1) {
930            int mask = n - 1;
931            int k = r;
932            boolean contended = false; // to retry loop if deq contends
933            for (int j = -n; j <= n; ++j) {
934                if (joinMe.status < 0)
935                    break outer;
936                int b;
937                ForkJoinTask<?>[] q;
938                ForkJoinWorkerThread v = ws[k & mask];
939                r ^= r << 13; r ^= r >>> 17; r ^= r << 5; // xorshift
940                if (v != null && (b=v.base) != v.sp && (q=v.queue) != null) {
941                    int i = (q.length - 1) & b;
942                    ForkJoinTask<?> t = q[i];
943                    if (t != null && UNSAFE.compareAndSwapObject
944                        (q, (i << qShift) + qBase, t, null)) {
945                        if (joinMe.status >= 0) {
946                            v.base = b + 1;
947                            seed = r;
948                            ++stealCount;
949                            return t;
950                        }
951                        UNSAFE.putObjectVolatile(q, (i<<qShift)+qBase, t);
952                        break outer; // back out
953                    }
954                    contended = true;
955                }
956                k = j < 0 ? r : (k + ((n >>> 1) | 1));
957            }
958            if (!contended && p.tryAwaitBusyJoin(joinMe))
959                break;
960        }
961        return null;
962    }
963
964    /**
965     * Version of popTask with join checks surrounding extraction.
966     * Uses the same backout strategy as helpJoinTask. Note that
967     * we ignore locallyFifo flag for local tasks here since helping
968     * joins only make sense in LIFO mode.
969     *
970     * @return a popped task, if available, unless joinMe is done
971     */
972    private ForkJoinTask<?> popWhileJoining(ForkJoinTask<?> joinMe) {
973        int s;
974        ForkJoinTask<?>[] q;
975        while ((s = sp) != base && (q = queue) != null && joinMe.status >= 0) {
976            int i = (q.length - 1) & --s;
977            ForkJoinTask<?> t = q[i];
978            if (t != null && UNSAFE.compareAndSwapObject
979                (q, (i << qShift) + qBase, t, null)) {
980                if (joinMe.status >= 0) {
981                    sp = s;
982                    return t;
983                }
984                UNSAFE.putObjectVolatile(q, (i << qShift) + qBase, t);
985                break;  // back out
986            }
987        }
988        return null;
989    }
990
991    /**
1117       * Runs tasks until {@code pool.isQuiescent()}.
1118       */
1119      final void helpQuiescePool() {
1120          for (;;) {
1121              ForkJoinTask<?> t = pollLocalTask();
1122 <            if (t != null || (t = scan()) != null)
1123 <                t.tryExec();
1122 >            if (t != null || (t = scan()) != null) {
1123 >                t.quietlyExec();
1124 >                currentSteal = null;
1125 >            }
1126              else {
1127                  ForkJoinPool p = pool;
1128 +                int a; // to inline CASes
1129                  if (active) {
1130 +                    if (!UNSAFE.compareAndSwapInt
1131 +                        (p, poolRunStateOffset, a = p.runState, a - 1))
1132 +                        continue;   // retry later
1133                      active = false; // inactivate
1003                    do {} while (!p.tryDecrementActiveCount());
1134                  }
1135                  if (p.isQuiescent()) {
1136                      active = true; // re-activate
1137 <                    do {} while (!p.tryIncrementActiveCount());
1137 >                    do {} while(!UNSAFE.compareAndSwapInt
1138 >                                (p, poolRunStateOffset, a = p.runState, a+1));
1139                      return;
1140                  }
1141              }
# Line 1014 | Line 1145 | public class ForkJoinWorkerThread extend
1145      // Unsafe mechanics
1146  
1147      private static final sun.misc.Unsafe UNSAFE = getUnsafe();
1148 +    private static final long spOffset =
1149 +        objectFieldOffset("sp", ForkJoinWorkerThread.class);
1150      private static final long runStateOffset =
1151          objectFieldOffset("runState", ForkJoinWorkerThread.class);
1152 +    private static final long currentJoinOffset =
1153 +        objectFieldOffset("currentJoin", ForkJoinWorkerThread.class);
1154 +    private static final long currentStealOffset =
1155 +        objectFieldOffset("currentSteal", ForkJoinWorkerThread.class);
1156      private static final long qBase =
1157          UNSAFE.arrayBaseOffset(ForkJoinTask[].class);
1158 +    private static final long poolRunStateOffset = // to inline CAS
1159 +        objectFieldOffset("runState", ForkJoinPool.class);
1160 +
1161      private static final int qShift;
1162  
1163      static {

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines