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

Comparing jsr166/src/jsr166y/Phaser.java (file contents):
Revision 1.50 by dl, Sat Nov 6 16:12:10 2010 UTC vs.
Revision 1.51 by dl, Sat Nov 13 00:55:51 2010 UTC

# Line 6 | Line 6
6  
7   package jsr166y;
8  
9 < import java.util.concurrent.*;
9 > import java.util.concurrent.TimeUnit;
10 > import java.util.concurrent.TimeoutException;
11   import java.util.concurrent.atomic.AtomicReference;
12   import java.util.concurrent.locks.LockSupport;
13  
# Line 226 | Line 227 | public class Phaser {
227       * Barrier state representation. Conceptually, a barrier contains
228       * four values:
229       *
230 <     * * parties -- the number of parties to wait (16 bits)
231 <     * * unarrived -- the number of parties yet to hit barrier (16 bits)
232 <     * * phase -- the generation of the barrier (31 bits)
233 <     * * terminated -- set if barrier is terminated (1 bit)
230 >     * * unarrived -- the number of parties yet to hit barrier (bits  0-15)
231 >     * * parties -- the number of parties to wait              (bits 16-31)
232 >     * * phase -- the generation of the barrier                (bits 32-62)
233 >     * * terminated -- set if barrier is terminated            (bit  63 / sign)
234       *
235       * However, to efficiently maintain atomicity, these values are
236       * packed into a single (atomic) long. Termination uses the sign
237       * bit of 32 bit representation of phase, so phase is set to -1 on
238       * termination. Good performance relies on keeping state decoding
239       * and encoding simple, and keeping race windows short.
239     *
240     * Note: there are some cheats in arrive() that rely on unarrived
241     * count being lowest 16 bits.
240       */
241      private volatile long state;
242  
243 <    private static final int ushortMask = 0xffff;
244 <    private static final int phaseMask  = 0x7fffffff;
243 >    private static final int  MAX_COUNT      = 0xffff;
244 >    private static final int  MAX_PHASE      = 0x7fffffff;
245 >    private static final int  PARTIES_SHIFT  = 16;
246 >    private static final int  PHASE_SHIFT    = 32;
247 >    private static final long UNARRIVED_MASK = 0xffffL;
248 >    private static final long PARTIES_MASK   = 0xffff0000L;
249 >    private static final long ONE_ARRIVAL    = 1L;
250 >    private static final long ONE_PARTY      = 1L << PARTIES_SHIFT;
251 >    private static final long TERMINATION_PHASE  = -1L << PHASE_SHIFT;
252 >
253 >    // The following unpacking methods are usually manually inlined
254  
255      private static int unarrivedOf(long s) {
256 <        return (int) (s & ushortMask);
256 >        return (int) (s & UNARRIVED_MASK);
257      }
258  
259      private static int partiesOf(long s) {
260 <        return ((int) s) >>> 16;
260 >        return ((int) (s & PARTIES_MASK)) >>> PARTIES_SHIFT;
261      }
262  
263      private static int phaseOf(long s) {
264 <        return (int) (s >>> 32);
264 >        return (int) (s >>> PHASE_SHIFT);
265      }
266  
267      private static int arrivedOf(long s) {
268          return partiesOf(s) - unarrivedOf(s);
269      }
270  
264    private static long stateFor(int phase, int parties, int unarrived) {
265        return ((((long) phase) << 32) | (((long) parties) << 16) |
266                (long) unarrived);
267    }
268
269    private static long trippedStateFor(int phase, int parties) {
270        long lp = (long) parties;
271        return (((long) phase) << 32) | (lp << 16) | lp;
272    }
273
274    /**
275     * Returns message string for bad bounds exceptions.
276     */
277    private static String badBounds(int parties, int unarrived) {
278        return ("Attempt to set " + unarrived +
279                " unarrived of " + parties + " parties");
280    }
281
271      /**
272       * The parent of this phaser, or null if none
273       */
# Line 290 | Line 279 | public class Phaser {
279       */
280      private final Phaser root;
281  
293    // Wait queues
294
282      /**
283       * Heads of Treiber stacks for waiting threads. To eliminate
284       * contention when releasing some threads while adding others, we
# Line 306 | Line 293 | public class Phaser {
293      }
294  
295      /**
296 <     * Returns current state, first resolving lagged propagation from
297 <     * root if necessary.
296 >     * Main implementation for methods arrive and arriveAndDeregister.
297 >     * Manually tuned to speed up and minimize race windows for the
298 >     * common case of just decrementing unarrived field.
299 >     *
300 >     * @param adj - adjustment to apply to state -- either
301 >     * ONE_ARRIVAL (for arrive) or
302 >     * ONE_ARRIVAL|ONE_PARTY (for arriveAndDeregister)
303 >     */
304 >    private int doArrive(long adj) {
305 >        long s;
306 >        int phase, unarrived;
307 >        while ((phase = (int)((s = state) >>> PHASE_SHIFT)) >= 0) {
308 >            if ((unarrived = (int)(s & UNARRIVED_MASK)) != 0) {
309 >                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s -= adj)) {
310 >                    if (unarrived == 1) {
311 >                        Phaser par;
312 >                        long p = s & PARTIES_MASK; // unshifted parties field
313 >                        long lu = p >>> PARTIES_SHIFT;
314 >                        int u = (int)lu;
315 >                        int nextPhase = (phase + 1) & MAX_PHASE;
316 >                        long next = ((long)nextPhase << PHASE_SHIFT) | p | lu;
317 >                        if ((par = parent) == null) {
318 >                            UNSAFE.compareAndSwapLong
319 >                                (this, stateOffset, s, onAdvance(phase, u)?
320 >                                 next | TERMINATION_PHASE : next);
321 >                            releaseWaiters(phase);
322 >                        }
323 >                        else {
324 >                            par.doArrive(u == 0?
325 >                                         ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL);
326 >                            if ((int)(par.state >>> PHASE_SHIFT) != nextPhase ||
327 >                                ((int)(state >>> PHASE_SHIFT) != nextPhase &&
328 >                                 !UNSAFE.compareAndSwapLong(this, stateOffset,
329 >                                                            s, next)))
330 >                                reconcileState();
331 >                        }
332 >                    }
333 >                    break;
334 >                }
335 >            }
336 >            else if (state == s && reconcileState() == s) // recheck
337 >                throw new IllegalStateException(badArrive());
338 >        }
339 >        return phase;
340 >    }
341 >
342 >    /**
343 >     * Returns message string for bounds exceptions on arrival.
344 >     * Declared out of-line from doArrive to reduce string op bulk.
345 >     */
346 >    private String badArrive() {
347 >        return ("Attempted arrival of unregistered party for " +
348 >                this.toString());
349 >    }
350 >
351 >    /**
352 >     * Implementation of register, bulkRegister
353 >     *
354 >     * @param registrations number to add to both parties and unarrived fields
355       */
356 <    private long getReconciledState() {
357 <        return (parent == null) ? state : reconcileState();
356 >    private int doRegister(int registrations) {
357 >        long adj = (long)registrations; // adjustment to state
358 >        adj |= adj << PARTIES_SHIFT;
359 >        Phaser par = parent;
360 >        long s;
361 >        int phase;
362 >        while ((phase = (int)((s = (par == null? state : reconcileState()))
363 >                              >>> PHASE_SHIFT)) >= 0) {
364 >            int parties = ((int)(s & PARTIES_MASK)) >>> PARTIES_SHIFT;
365 >            if (parties != 0 && (s & UNARRIVED_MASK) == 0)
366 >                internalAwaitAdvance(phase, null); // wait for onAdvance
367 >            else if (parties + registrations > MAX_COUNT)
368 >                throw new IllegalStateException(badRegister());
369 >            else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s + adj))
370 >                break;
371 >        }
372 >        return phase;
373 >    }
374 >
375 >    /**
376 >     * Returns message string for bounds exceptions on registration
377 >     */
378 >    private String badRegister() {
379 >        return ("Attempt to register more than " + MAX_COUNT + " parties for "+
380 >                this.toString());
381      }
382  
383      /**
384 <     * Recursively resolves state.
384 >     * Recursively resolves lagged phase propagation from root if
385 >     * necessary.
386       */
387      private long reconcileState() {
388          Phaser par = parent;
389 <        long s = state;
390 <        if (par != null) {
391 <            int phase, rootPhase;
392 <            while ((phase = phaseOf(s)) >= 0 &&
393 <                   (rootPhase = phaseOf(root.state)) != phase &&
394 <                   (rootPhase < 0 || unarrivedOf(s) == 0)) {
395 <                int parentPhase = phaseOf(par.getReconciledState());
396 <                if (parentPhase != phase) {
397 <                    long next = trippedStateFor(parentPhase, partiesOf(s));
398 <                    if (state == s)
399 <                        UNSAFE.compareAndSwapLong(this, stateOffset, s, next);
389 >        if (par == null)
390 >            return state;
391 >        Phaser rt = root;
392 >        long s;
393 >        int phase, rPhase;
394 >        while ((phase = (int)((s = state) >>> PHASE_SHIFT)) >= 0 &&
395 >               (rPhase = (int)(rt.state >>> PHASE_SHIFT)) != phase) {
396 >            if (rPhase < 0 || (s & UNARRIVED_MASK) == 0) {
397 >                long ps = par.parent == null? par.state : par.reconcileState();
398 >                int pPhase = (int)(ps >>> PHASE_SHIFT);
399 >                if (pPhase < 0 || pPhase == ((phase + 1) & MAX_PHASE)) {
400 >                    if (state != s)
401 >                        continue;
402 >                    long p = s & PARTIES_MASK;
403 >                    long next = ((((long) pPhase) << PHASE_SHIFT) |
404 >                                 (p >>> PARTIES_SHIFT) | p);
405 >                    if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
406 >                        return next;
407                  }
333                s = state;
408              }
409 +            if (state == s)
410 +                releaseWaiters(phase); // help release others
411          }
412          return s;
413      }
# Line 381 | Line 457 | public class Phaser {
457       * or greater than the maximum number of parties supported
458       */
459      public Phaser(Phaser parent, int parties) {
460 <        if (parties < 0 || parties > ushortMask)
460 >        if (parties < 0 || parties > MAX_COUNT)
461              throw new IllegalArgumentException("Illegal number of parties");
462          int phase;
463          this.parent = parent;
# Line 398 | Line 474 | public class Phaser {
474              this.oddQ = new AtomicReference<QNode>();
475              phase = 0;
476          }
477 <        this.state = trippedStateFor(phase, parties);
477 >        long p = (long)parties;
478 >        this.state = (((long) phase) << PHASE_SHIFT) | p | (p << PARTIES_SHIFT);
479      }
480  
481      /**
# Line 428 | Line 505 | public class Phaser {
505      public int bulkRegister(int parties) {
506          if (parties < 0)
507              throw new IllegalArgumentException();
508 +        if (parties > MAX_COUNT)
509 +            throw new IllegalStateException(badRegister());
510          if (parties == 0)
511              return getPhase();
512          return doRegister(parties);
513      }
514  
515      /**
437     * Shared code for register, bulkRegister
438     */
439    private int doRegister(int registrations) {
440        Phaser par = parent;
441        long s;
442        int phase;
443        while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
444            int p = partiesOf(s);
445            int u = unarrivedOf(s);
446            int unarrived = u + registrations;
447            int parties = p + registrations;
448            if (u == 0 && p != 0)  // if tripped, wait for advance
449                untimedWait(phase);
450            else if (parties > ushortMask)
451                throw new IllegalStateException(badBounds(parties, unarrived));
452            else if (par == null || phaseOf(root.state) == phase) {
453                long next = stateFor(phase, parties, unarrived);
454                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
455                    break;
456            }
457        }
458        return phase;
459    }
460
461    /**
516       * Arrives at the barrier, but does not wait for others.  (You can
517       * in turn wait for others via {@link #awaitAdvance}).  It is an
518       * unenforced usage error for an unregistered party to invoke this
# Line 469 | Line 523 | public class Phaser {
523       * of unarrived parties would become negative
524       */
525      public int arrive() {
526 <        Phaser par = parent;
473 <        long s;
474 <        int phase;
475 <        while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
476 <            int parties = partiesOf(s);
477 <            int unarrived = unarrivedOf(s) - 1;
478 <            if (unarrived > 0) {                // Not the last arrival
479 <                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s - 1))
480 <                    break;                      // s-1 adds one arrival
481 <            }
482 <            else if (unarrived < 0)
483 <                throw new IllegalStateException(badBounds(parties, unarrived));
484 <            else if (par == null) {             // directly trip
485 <                long next = trippedStateFor(onAdvance(phase, parties) ? -1 :
486 <                                            ((phase + 1) & phaseMask),
487 <                                            parties);
488 <                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next)) {
489 <                    releaseWaiters(phase);
490 <                    break;
491 <                }
492 <            }
493 <            else if (phaseOf(root.state) == phase &&
494 <                     UNSAFE.compareAndSwapLong(this, stateOffset, s, s - 1)) {
495 <                par.arrive();                   // cascade to parent
496 <                reconcileState();
497 <                break;
498 <            }
499 <        }
500 <        return phase;
526 >        return doArrive(ONE_ARRIVAL);
527      }
528  
529      /**
# Line 514 | Line 540 | public class Phaser {
540       * of registered or unarrived parties would become negative
541       */
542      public int arriveAndDeregister() {
543 <        // similar to arrive, but too different to merge
518 <        Phaser par = parent;
519 <        long s;
520 <        int phase;
521 <        while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
522 <            int parties = partiesOf(s) - 1;
523 <            int unarrived = unarrivedOf(s) - 1;
524 <            if (unarrived > 0) {
525 <                long next = stateFor(phase, parties, unarrived);
526 <                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
527 <                    break;
528 <            }
529 <            else if (unarrived < 0)
530 <                throw new IllegalStateException(badBounds(parties, unarrived));
531 <            else if (par == null) {
532 <                long next = trippedStateFor(onAdvance(phase, parties)? -1:
533 <                                            (phase + 1) & phaseMask,
534 <                                            parties);
535 <                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next)) {
536 <                    releaseWaiters(phase);
537 <                    break;
538 <                }
539 <            }
540 <            else if (phaseOf(root.state) == phase) {
541 <                long next = stateFor(phase, parties, 0);
542 <                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next)) {
543 <                    if (parties == 0)
544 <                        par.arriveAndDeregister();
545 <                    else
546 <                        par.arrive();
547 <                    reconcileState();
548 <                    break;
549 <                }
550 <            }
551 <        }
552 <        return phase;
543 >        return doArrive(ONE_ARRIVAL|ONE_PARTY);
544      }
545  
546      /**
# Line 584 | Line 575 | public class Phaser {
575      public int awaitAdvance(int phase) {
576          if (phase < 0)
577              return phase;
578 <        int p = getPhase();
578 >        int p = (int)((parent==null? state : reconcileState()) >>> PHASE_SHIFT);
579          if (p != phase)
580              return p;
581 <        return untimedWait(phase);
581 >        return internalAwaitAdvance(phase, null);
582      }
583  
584      /**
# Line 608 | Line 599 | public class Phaser {
599          throws InterruptedException {
600          if (phase < 0)
601              return phase;
602 <        int p = getPhase();
602 >        int p = (int)((parent==null? state : reconcileState()) >>> PHASE_SHIFT);
603          if (p != phase)
604              return p;
605 <        return interruptibleWait(phase);
605 >        QNode node = new QNode(this, phase, true, false, 0L);
606 >        p = internalAwaitAdvance(phase, node);
607 >        if (node.wasInterrupted)
608 >            throw new InterruptedException();
609 >        else
610 >            return p;
611      }
612  
613      /**
# Line 640 | Line 636 | public class Phaser {
636          long nanos = unit.toNanos(timeout);
637          if (phase < 0)
638              return phase;
639 <        int p = getPhase();
639 >        int p = (int)((parent==null? state : reconcileState()) >>> PHASE_SHIFT);
640          if (p != phase)
641              return p;
642 <        return timedWait(phase, nanos);
642 >        QNode node = new QNode(this, phase, true, true, nanos);
643 >        p = internalAwaitAdvance(phase, node);
644 >        if (node.wasInterrupted)
645 >            throw new InterruptedException();
646 >        else if (p == phase)
647 >            throw new TimeoutException();
648 >        else
649 >            return p;
650      }
651  
652      /**
# Line 656 | Line 659 | public class Phaser {
659      public void forceTermination() {
660          Phaser r = root;    // force at root then reconcile
661          long s;
662 <        while (phaseOf(s = r.state) >= 0)
663 <            UNSAFE.compareAndSwapLong(r, stateOffset, s,
661 <                                      stateFor(-1, partiesOf(s),
662 <                                               unarrivedOf(s)));
662 >        while ((s = r.state) >= 0)
663 >            UNSAFE.compareAndSwapLong(r, stateOffset, s, s | TERMINATION_PHASE);
664          reconcileState();
665 <        releaseWaiters(0);  // ensure wakeups on both queues
665 >        releaseWaiters(0); // signal all threads
666          releaseWaiters(1);
667      }
668  
# Line 673 | Line 674 | public class Phaser {
674       * @return the phase number, or a negative value if terminated
675       */
676      public final int getPhase() {
677 <        return phaseOf(getReconciledState());
677 >        return (int)((parent == null? state : reconcileState()) >>> PHASE_SHIFT);
678      }
679  
680      /**
# Line 682 | Line 683 | public class Phaser {
683       * @return the number of parties
684       */
685      public int getRegisteredParties() {
686 <        return partiesOf(getReconciledState());
686 >        return partiesOf(parent == null? state : reconcileState());
687      }
688  
689      /**
# Line 692 | Line 693 | public class Phaser {
693       * @return the number of arrived parties
694       */
695      public int getArrivedParties() {
696 <        return arrivedOf(getReconciledState());
696 >        return arrivedOf(parent == null? state : reconcileState());
697      }
698  
699      /**
# Line 702 | Line 703 | public class Phaser {
703       * @return the number of unarrived parties
704       */
705      public int getUnarrivedParties() {
706 <        return unarrivedOf(getReconciledState());
706 >        return unarrivedOf(parent == null? state : reconcileState());
707      }
708  
709      /**
# Line 730 | Line 731 | public class Phaser {
731       * @return {@code true} if this barrier has been terminated
732       */
733      public boolean isTerminated() {
734 <        return getPhase() < 0;
734 >        return (parent == null? state : reconcileState()) < 0;
735      }
736  
737      /**
# Line 746 | Line 747 | public class Phaser {
747       * which case no advance occurs.
748       *
749       * <p>The arguments to this method provide the state of the phaser
750 <     * prevailing for the current transition.  The results and effects
751 <     * of invoking phase-related methods (including {@code getPhase}
751 <     * as well as arrival, registration, and waiting methods) from
750 >     * prevailing for the current transition.  The effects of invoking
751 >     * arrival, registration, and waiting methods on this Phaser from
752       * within {@code onAdvance} are unspecified and should not be
753 <     * relied on. Similarly, while it is possible to override this
754 <     * method to produce side-effects visible to participating tasks,
755 <     * it is in general safe to do so only in designs in which all
756 <     * parties register before any arrive, and all {@link
757 <     * #awaitAdvance} at each phase.
753 >     * relied on.
754 >     *
755 >     * <p>If this Phaser is a member of a tiered set of Phasers, then
756 >     * {@code onAdvance} is invoked only for its root Phaser on each
757 >     * advance.
758       *
759       * <p>The default version returns {@code true} when the number of
760       * registered parties is zero. Normally, overrides that arrange
# Line 779 | Line 779 | public class Phaser {
779       * @return a string identifying this barrier, as well as its state
780       */
781      public String toString() {
782 <        long s = getReconciledState();
782 >        long s = reconcileState();
783          return super.toString() +
784              "[phase = " + phaseOf(s) +
785              " parties = " + partiesOf(s) +
786              " arrived = " + arrivedOf(s) + "]";
787      }
788  
789    // methods for waiting
790
789      /**
790 <     * Wait nodes for Treiber stack representing wait queue
793 <     */
794 <    static final class QNode implements ForkJoinPool.ManagedBlocker {
795 <        final Phaser phaser;
796 <        final int phase;
797 <        final long startTime;
798 <        final long nanos;
799 <        final boolean timed;
800 <        final boolean interruptible;
801 <        volatile boolean wasInterrupted = false;
802 <        volatile Thread thread; // nulled to cancel wait
803 <        QNode next;
804 <
805 <        QNode(Phaser phaser, int phase, boolean interruptible,
806 <              boolean timed, long startTime, long nanos) {
807 <            this.phaser = phaser;
808 <            this.phase = phase;
809 <            this.timed = timed;
810 <            this.interruptible = interruptible;
811 <            this.startTime = startTime;
812 <            this.nanos = nanos;
813 <            thread = Thread.currentThread();
814 <        }
815 <
816 <        public boolean isReleasable() {
817 <            return (thread == null ||
818 <                    phaser.getPhase() != phase ||
819 <                    (interruptible && wasInterrupted) ||
820 <                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
821 <        }
822 <
823 <        public boolean block() {
824 <            if (Thread.interrupted()) {
825 <                wasInterrupted = true;
826 <                if (interruptible)
827 <                    return true;
828 <            }
829 <            if (!timed)
830 <                LockSupport.park(this);
831 <            else {
832 <                long waitTime = nanos - (System.nanoTime() - startTime);
833 <                if (waitTime <= 0)
834 <                    return true;
835 <                LockSupport.parkNanos(this, waitTime);
836 <            }
837 <            return isReleasable();
838 <        }
839 <
840 <        void signal() {
841 <            Thread t = thread;
842 <            if (t != null) {
843 <                thread = null;
844 <                LockSupport.unpark(t);
845 <            }
846 <        }
847 <
848 <        boolean doWait() {
849 <            if (thread != null) {
850 <                try {
851 <                    ForkJoinPool.managedBlock(this);
852 <                } catch (InterruptedException ie) {
853 <                    wasInterrupted = true; // can't currently happen
854 <                }
855 <            }
856 <            return wasInterrupted;
857 <        }
858 <    }
859 <
860 <    /**
861 <     * Removes and signals waiting threads from wait queue.
790 >     * Removes and signals threads from queue for phase
791       */
792      private void releaseWaiters(int phase) {
793          AtomicReference<QNode> head = queueFor(phase);
794          QNode q;
795 <        while ((q = head.get()) != null) {
795 >        int p;
796 >        while ((q = head.get()) != null &&
797 >               ((p = q.phase) == phase ||
798 >                (int)(root.state >>> PHASE_SHIFT) != p)) {
799              if (head.compareAndSet(q, q.next))
800                  q.signal();
801          }
# Line 874 | Line 806 | public class Phaser {
806       *
807       * @return true if successful
808       */
809 <    private boolean tryEnqueue(QNode node) {
810 <        AtomicReference<QNode> head = queueFor(node.phase);
811 <        return head.compareAndSet(node.next = head.get(), node);
809 >    private boolean tryEnqueue(int phase, QNode node) {
810 >        releaseWaiters(phase-1); // ensure old queue clean
811 >        AtomicReference<QNode> head = queueFor(phase);
812 >        QNode q = head.get();
813 >        return ((q == null || q.phase == phase) &&
814 >                (int)(root.state >>> PHASE_SHIFT) == phase &&
815 >                head.compareAndSet(node.next = q, node));
816      }
817  
818 +    /** The number of CPUs, for spin control */
819 +    private static final int NCPU = Runtime.getRuntime().availableProcessors();
820 +
821      /**
822 <     * The number of times to spin before blocking waiting for advance.
822 >     * The number of times to spin before blocking while waiting for
823 >     * advance, per arrival while waiting. On multiprocessors, fully
824 >     * blocking and waking up a large number of threads all at once is
825 >     * usually a very slow process, so we use rechargeable spins to
826 >     * avoid it when threads regularly arrive: When a thread in
827 >     * internalAwaitAdvance notices another arrival before blocking,
828 >     * and there appear to be enough CPUs available, it spins
829 >     * SPINS_PER_ARRIVAL more times before continuing to try to
830 >     * block. The value trades off good-citizenship vs big unnecessary
831 >     * slowdowns.
832       */
833 <    static final int MAX_SPINS =
886 <        Runtime.getRuntime().availableProcessors() == 1 ? 0 : 1 << 8;
833 >    static final int SPINS_PER_ARRIVAL = NCPU < 2? 1 : 1 << 8;
834  
835      /**
836 <     * Enqueues node and waits unless aborted or signalled.
836 >     * Possibly blocks and waits for phase to advance unless aborted.
837       *
838 +     * @param phase current phase
839 +     * @param node if nonnull, the wait node to track interrupt and timeout;
840 +     * if null, denotes noninterruptible wait
841       * @return current phase
842       */
843 <    private int untimedWait(int phase) {
844 <        QNode node = null;
843 >    private int internalAwaitAdvance(int phase, QNode node) {
844 >        Phaser current = this;       // to eventually wait at root if tiered
845 >        Phaser par = parent;
846          boolean queued = false;
847 <        boolean interrupted = false;
848 <        int spins = MAX_SPINS;
847 >        int spins = SPINS_PER_ARRIVAL;
848 >        int lastUnarrived = -1;      // to increase spins upon change
849 >        long s;
850          int p;
851 <        while ((p = getPhase()) == phase) {
852 <            if (Thread.interrupted())
853 <                interrupted = true;
854 <            else if (spins > 0) {
855 <                if (--spins == 0)
856 <                    Thread.yield();
851 >        while ((p = (int)((s = current.state) >>> PHASE_SHIFT)) == phase) {
852 >            int unarrived = (int)(s & UNARRIVED_MASK);
853 >            if (unarrived != lastUnarrived) {
854 >                if ((lastUnarrived = unarrived) < NCPU)
855 >                    spins += SPINS_PER_ARRIVAL;
856 >            }
857 >            else if (unarrived == 0 && par != null) {
858 >                current = par;       // if all arrived, use parent
859 >                par = par.parent;
860              }
861 +            else if (spins > 0)
862 +                --spins;
863              else if (node == null)
864 <                node = new QNode(this, phase, false, false, 0, 0);
864 >                node = new QNode(this, phase, false, false, 0L);
865 >            else if (node.isReleasable())
866 >                break;
867              else if (!queued)
868 <                queued = tryEnqueue(node);
869 <            else if (node.doWait())
870 <                interrupted = true;
871 <        }
872 <        if (node != null)
873 <            node.thread = null;
874 <        releaseWaiters(phase);
916 <        if (interrupted)
917 <            Thread.currentThread().interrupt();
918 <        return p;
919 <    }
920 <
921 <    /**
922 <     * Interruptible version
923 <     * @return current phase
924 <     */
925 <    private int interruptibleWait(int phase) throws InterruptedException {
926 <        QNode node = null;
927 <        boolean queued = false;
928 <        boolean interrupted = false;
929 <        int spins = MAX_SPINS;
930 <        int p;
931 <        while ((p = getPhase()) == phase && !interrupted) {
932 <            if (Thread.interrupted())
933 <                interrupted = true;
934 <            else if (spins > 0) {
935 <                if (--spins == 0)
936 <                    Thread.yield();
868 >                queued = tryEnqueue(phase, node);
869 >            else {
870 >                try {
871 >                    ForkJoinPool.managedBlock(node);
872 >                } catch (InterruptedException ie) {
873 >                    node.wasInterrupted = true;
874 >                }
875              }
876 <            else if (node == null)
877 <                node = new QNode(this, phase, true, false, 0, 0);
878 <            else if (!queued)
879 <                queued = tryEnqueue(node);
880 <            else if (node.doWait())
881 <                interrupted = true;
882 <        }
883 <        if (node != null)
884 <            node.thread = null;
885 <        if (p != phase || (p = getPhase()) != phase)
876 >        }
877 >        if (node != null) {
878 >            if (node.thread != null)
879 >                node.thread = null;
880 >            if (!node.interruptible && node.wasInterrupted)
881 >                Thread.currentThread().interrupt();
882 >        }
883 >        if (p == phase && parent != null)
884 >            p = (int)(reconcileState() >>> PHASE_SHIFT);
885 >        if (p != phase)
886              releaseWaiters(phase);
949        if (interrupted)
950            throw new InterruptedException();
887          return p;
888      }
889  
890      /**
891 <     * Timeout version.
956 <     * @return current phase
891 >     * Wait nodes for Treiber stack representing wait queue
892       */
893 <    private int timedWait(int phase, long nanos)
894 <        throws InterruptedException, TimeoutException {
895 <        long startTime = System.nanoTime();
896 <        QNode node = null;
897 <        boolean queued = false;
898 <        boolean interrupted = false;
899 <        int spins = MAX_SPINS;
900 <        int p;
901 <        while ((p = getPhase()) == phase && !interrupted) {
902 <            if (Thread.interrupted())
903 <                interrupted = true;
904 <            else if (nanos - (System.nanoTime() - startTime) <= 0)
905 <                break;
906 <            else if (spins > 0) {
907 <                if (--spins == 0)
908 <                    Thread.yield();
893 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
894 >        final Phaser phaser;
895 >        final int phase;
896 >        final boolean interruptible;
897 >        final boolean timed;
898 >        boolean wasInterrupted;
899 >        long nanos;
900 >        long lastTime;
901 >        volatile Thread thread; // nulled to cancel wait
902 >        QNode next;
903 >
904 >        QNode(Phaser phaser, int phase, boolean interruptible,
905 >              boolean timed, long nanos) {
906 >            this.phaser = phaser;
907 >            this.phase = phase;
908 >            this.interruptible = interruptible;
909 >            this.nanos = nanos;
910 >            this.timed = timed;
911 >            this.lastTime = timed? System.nanoTime() : 0L;
912 >            thread = Thread.currentThread();
913 >        }
914 >
915 >        public boolean isReleasable() {
916 >            Thread t = thread;
917 >            if (t != null) {
918 >                if (phaser.getPhase() != phase)
919 >                    t = null;
920 >                else {
921 >                    if (Thread.interrupted())
922 >                        wasInterrupted = true;
923 >                    if (interruptible && wasInterrupted)
924 >                        t = null;
925 >                    else if (timed) {
926 >                        if (nanos > 0) {
927 >                            long now = System.nanoTime();
928 >                            nanos -= now - lastTime;
929 >                            lastTime = now;
930 >                        }
931 >                        if (nanos <= 0)
932 >                            t = null;
933 >                    }
934 >                }
935 >                if (t != null)
936 >                    return false;
937 >                thread = null;
938              }
939 <            else if (node == null)
940 <                node = new QNode(this, phase, true, true, startTime, nanos);
941 <            else if (!queued)
942 <                queued = tryEnqueue(node);
943 <            else if (node.doWait())
944 <                interrupted = true;
945 <        }
946 <        if (node != null)
947 <            node.thread = null;
948 <        if (p != phase || (p = getPhase()) != phase)
949 <            releaseWaiters(phase);
950 <        if (interrupted)
951 <            throw new InterruptedException();
952 <        if (p == phase)
953 <            throw new TimeoutException();
954 <        return p;
939 >            return true;
940 >        }
941 >
942 >        public boolean block() {
943 >            if (isReleasable())
944 >                return true;
945 >            else if (!timed)
946 >                LockSupport.park(this);
947 >            else if (nanos > 0)
948 >                LockSupport.parkNanos(this, nanos);
949 >            return isReleasable();
950 >        }
951 >
952 >        void signal() {
953 >            Thread t = thread;
954 >            if (t != null) {
955 >                thread = null;
956 >                LockSupport.unpark(t);
957 >            }
958 >        }
959      }
960  
961      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines