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.6 by dl, Tue Oct 28 23:03:24 2008 UTC vs.
Revision 1.11 by jsr166, Thu Mar 19 04:49:44 2009 UTC

# Line 5 | Line 5
5   */
6  
7   package jsr166y;
8 +
9   import java.util.concurrent.*;
10   import java.util.concurrent.atomic.*;
11   import java.util.concurrent.locks.LockSupport;
# Line 13 | Line 14 | import java.lang.reflect.*;
14  
15   /**
16   * A reusable synchronization barrier, similar in functionality to a
17 < * {@link java.util.concurrent.CyclicBarrier} and {@link
18 < * java.util.concurrent.CountDownLatch} but supporting more flexible
19 < * usage.
17 > * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
18 > * {@link java.util.concurrent.CountDownLatch CountDownLatch}
19 > * but supporting more flexible usage.
20   *
21   * <ul>
22   *
# Line 25 | Line 26 | import java.lang.reflect.*;
26   * basic synchronization constructs, registration and deregistration
27   * affect only internal counts; they do not establish any further
28   * internal bookkeeping, so tasks cannot query whether they are
29 < * registered. (However, you can introduce such bookkeeping in by
29 > * registered. (However, you can introduce such bookkeeping by
30   * subclassing this class.)
31   *
32   * <li> Each generation has an associated phase value, starting at
33   * zero, and advancing when all parties reach the barrier (wrapping
34 < * around to zero after reaching <tt>Integer.MAX_VALUE</tt>).
34 > * around to zero after reaching {@code Integer.MAX_VALUE}).
35   *
36   * <li> Like a CyclicBarrier, a Phaser may be repeatedly awaited.
37 < * Method <tt>arriveAndAwaitAdvance</tt> has effect analogous to
38 < * <tt>CyclicBarrier.await</tt>.  However, Phasers separate two
37 > * Method {@code arriveAndAwaitAdvance} has effect analogous to
38 > * {@code CyclicBarrier.await}.  However, Phasers separate two
39   * aspects of coordination, that may also be invoked independently:
40   *
41   * <ul>
42   *
43 < *   <li> Arriving at a barrier. Methods <tt>arrive</tt> and
44 < *       <tt>arriveAndDeregister</tt> do not block, but return
43 > *   <li> Arriving at a barrier. Methods {@code arrive} and
44 > *       {@code arriveAndDeregister} do not block, but return
45   *       the phase value current upon entry to the method.
46   *
47 < *   <li> Awaiting others. Method <tt>awaitAdvance</tt> requires an
47 > *   <li> Awaiting others. Method {@code awaitAdvance} requires an
48   *       argument indicating the entry phase, and returns when the
49   *       barrier advances to a new phase.
50   * </ul>
# Line 51 | Line 52 | import java.lang.reflect.*;
52   *
53   * <li> Barrier actions, performed by the task triggering a phase
54   * advance while others may be waiting, are arranged by overriding
55 < * method <tt>onAdvance</tt>, that also controls termination.
55 > * method {@code onAdvance}, that also controls termination.
56   * Overriding this method may be used to similar but more flexible
57   * effect as providing a barrier action to a CyclicBarrier.
58   *
59   * <li> Phasers may enter a <em>termination</em> state in which all
60 < * await actions immediately return, indicating (via a negative phase
61 < * value) that execution is complete.  Termination is triggered by
62 < * executing the overridable <tt>onAdvance</tt> method that is invoked
63 < * each time the barrier is about to be tripped. When a Phaser is
64 < * controlling an action with a fixed number of iterations, it is
65 < * often convenient to override this method to cause termination when
66 < * the current phase number reaches a threshold. Method
67 < * <tt>forceTermination</tt> is also available to abruptly release
68 < * waiting threads and allow them to terminate.
60 > * actions immediately return without updating phaser state or waiting
61 > * for advance, and indicating (via a negative phase value) that
62 > * execution is complete.  Termination is triggered by executing the
63 > * overridable {@code onAdvance} method that is invoked each time the
64 > * barrier is about to be tripped. When a Phaser is controlling an
65 > * action with a fixed number of iterations, it is often convenient to
66 > * override this method to cause termination when the current phase
67 > * number reaches a threshold. Method {@code forceTermination} is also
68 > * available to abruptly release waiting threads and allow them to
69 > * terminate.
70   *
71   * <li> Phasers may be tiered to reduce contention. Phasers with large
72   * numbers of parties that would otherwise experience heavy
# Line 72 | Line 74 | import java.lang.reflect.*;
74   * This will typically greatly increase throughput even though it
75   * incurs somewhat greater per-operation overhead.
76   *
77 < * <li> By default, <tt>awaitAdvance</tt> continues to wait even if
77 > * <li> By default, {@code awaitAdvance} continues to wait even if
78   * the waiting thread is interrupted. And unlike the case in
79   * CyclicBarriers, exceptions encountered while tasks wait
80   * interruptibly or with timeout do not change the state of the
81   * barrier. If necessary, you can perform any associated recovery
82   * within handlers of those exceptions, often after invoking
83 < * <tt>forceTermination</tt>.
83 > * {@code forceTermination}.
84 > *
85 > * <li>Phasers ensure lack of starvation when used by ForkJoinTasks.
86   *
87   * </ul>
88   *
89   * <p><b>Sample usages:</b>
90   *
91 < * <p>A Phaser may be used instead of a <tt>CountdownLatch</tt> to control
91 > * <p>A Phaser may be used instead of a {@code CountDownLatch} to control
92   * a one-shot action serving a variable number of parties. The typical
93   * idiom is for the method setting this up to first register, then
94   * start the actions, then deregister, as in:
# Line 108 | Line 112 | import java.lang.reflect.*;
112   *   int p = phaser.arriveAndDeregister(); // deregister self  ...
113   *   p = phaser.awaitAdvance(p); // ... and await arrival
114   *   otherActions(); // do other things while tasks execute
115 < *   phaser.awaitAdvance(p); // awit final completion
115 > *   phaser.awaitAdvance(p); // await final completion
116   * }
117   * </pre>
118   *
119   * <p>One way to cause a set of threads to repeatedly perform actions
120 < * for a given number of iterations is to override <tt>onAdvance</tt>:
120 > * for a given number of iterations is to override {@code onAdvance}:
121   *
122   * <pre>
123   *  void startTasks(List&lt;Runnable&gt; list, final int iterations) {
# Line 163 | Line 167 | import java.lang.reflect.*;
167   *  build(new Task[n], 0, n, new Phaser());
168   * </pre>
169   *
170 < * The best value of <tt>TASKS_PER_PHASER</tt> depends mainly on
170 > * The best value of {@code TASKS_PER_PHASER} depends mainly on
171   * expected barrier synchronization rates. A value as low as four may
172   * be appropriate for extremely small per-barrier task bodies (thus
173   * high rates), or up to hundreds for extremely large ones.
# Line 195 | Line 199 | public class Phaser {
199       * However, to efficiently maintain atomicity, these values are
200       * packed into a single (atomic) long. Termination uses the sign
201       * bit of 32 bit representation of phase, so phase is set to -1 on
202 <     * termination. Good performace relies on keeping state decoding
202 >     * termination. Good performance relies on keeping state decoding
203       * and encoding simple, and keeping race windows short.
204       *
205       * Note: there are some cheats in arrive() that rely on unarrived
206 <     * being lowest 16 bits.
206 >     * count being lowest 16 bits.
207       */
208      private volatile long state;
209  
210      private static final int ushortBits = 16;
211 <    private static final int ushortMask =  (1 << ushortBits) - 1;
212 <    private static final int phaseMask = 0x7fffffff;
211 >    private static final int ushortMask = 0xffff;
212 >    private static final int phaseMask  = 0x7fffffff;
213  
214      private static int unarrivedOf(long s) {
215          return (int)(s & ushortMask);
216      }
217  
218      private static int partiesOf(long s) {
219 <        return (int)(s & (ushortMask << 16)) >>> 16;
219 >        return ((int)s) >>> 16;
220      }
221  
222      private static int phaseOf(long s) {
# Line 224 | Line 228 | public class Phaser {
228      }
229  
230      private static long stateFor(int phase, int parties, int unarrived) {
231 <        return (((long)phase) << 32) | ((parties << 16) | unarrived);
231 >        return ((((long)phase) << 32) | (((long)parties) << 16) |
232 >                (long)unarrived);
233      }
234  
235      private static long trippedStateFor(int phase, int parties) {
236 <        return (((long)phase) << 32) | ((parties << 16) | parties);
236 >        long lp = (long)parties;
237 >        return (((long)phase) << 32) | (lp << 16) | lp;
238      }
239  
240 <    private static IllegalStateException badBounds(int parties, int unarrived) {
241 <        return new IllegalStateException
242 <            ("Attempt to set " + unarrived +
243 <             " unarrived of " + parties + " parties");
240 >    /**
241 >     * Returns message string for bad bounds exceptions
242 >     */
243 >    private static String badBounds(int parties, int unarrived) {
244 >        return ("Attempt to set " + unarrived +
245 >                " unarrived of " + parties + " parties");
246      }
247  
248      /**
# Line 251 | Line 259 | public class Phaser {
259      // Wait queues
260  
261      /**
262 <     * Heads of Treiber stacks waiting for nonFJ threads. To eliminate
262 >     * Heads of Treiber stacks for waiting threads. To eliminate
263       * contention while releasing some threads while adding others, we
264       * use two of them, alternating across even and odd phases.
265       */
# Line 295 | Line 303 | public class Phaser {
303  
304      /**
305       * Creates a new Phaser without any initially registered parties,
306 <     * initial phase number 0, and no parent.
306 >     * initial phase number 0, and no parent. Any thread using this
307 >     * Phaser will need to first register for it.
308       */
309      public Phaser() {
310          this(null);
# Line 390 | Line 399 | public class Phaser {
399              phase = phaseOf(s);
400              int unarrived = unarrivedOf(s) + registrations;
401              int parties = partiesOf(s) + registrations;
402 <            if (phase < 0)
402 >            if (phase < 0)
403                  break;
404              if (parties > ushortMask || unarrived > ushortMask)
405 <                throw badBounds(parties, unarrived);
405 >                throw new IllegalStateException(badBounds(parties, unarrived));
406              if (phase == phaseOf(root.state) &&
407                  casState(s, stateFor(phase, parties, unarrived)))
408                  break;
# Line 415 | Line 424 | public class Phaser {
424          for (;;) {
425              long s = state;
426              phase = phaseOf(s);
427 +            if (phase < 0)
428 +                break;
429              int parties = partiesOf(s);
430              int unarrived = unarrivedOf(s) - 1;
431              if (unarrived > 0) {        // Not the last arrival
# Line 440 | Line 451 | public class Phaser {
451                      }
452                  }
453              }
443            else if (phase < 0) // Don't throw exception if terminated
444                break;
454              else if (phase != phaseOf(root.state)) // or if unreconciled
455                  reconcileState();
456              else
457 <                throw badBounds(parties, unarrived);
457 >                throw new IllegalStateException(badBounds(parties, unarrived));
458          }
459          return phase;
460      }
# Line 469 | Line 478 | public class Phaser {
478          for (;;) {
479              long s = state;
480              phase = phaseOf(s);
481 +            if (phase < 0)
482 +                break;
483              int parties = partiesOf(s) - 1;
484              int unarrived = unarrivedOf(s) - 1;
485              if (parties >= 0) {
# Line 494 | Line 505 | public class Phaser {
505                      }
506                      continue;
507                  }
497                if (phase < 0)
498                    break;
508                  if (par != null && phase != phaseOf(root.state)) {
509                      reconcileState();
510                      continue;
511                  }
512              }
513 <            throw badBounds(parties, unarrived);
513 >            throw new IllegalStateException(badBounds(parties, unarrived));
514          }
515          return phase;
516      }
517  
518      /**
519       * Arrives at the barrier and awaits others. Equivalent in effect
520 <     * to <tt>awaitAdvance(arrive())</tt>.  If you instead need to
520 >     * to {@code awaitAdvance(arrive())}.  If you instead need to
521       * await with interruption of timeout, and/or deregister upon
522       * arrival, you can arrange them using analogous constructions.
523       * @return the phase on entry to this method
# Line 533 | Line 542 | public class Phaser {
542          int p = phaseOf(s);
543          if (p != phase)
544              return p;
545 <        if (unarrivedOf(s) == 0)
545 >        if (unarrivedOf(s) == 0 && parent != null)
546              parent.awaitAdvance(phase);
547          // Fall here even if parent waited, to reconcile and help release
548          return untimedWait(phase);
# Line 541 | Line 550 | public class Phaser {
550  
551      /**
552       * Awaits the phase of the barrier to advance from the given
553 <     * value, or returns immediately if argumet is negative or this
553 >     * value, or returns immediately if argument is negative or this
554       * barrier is terminated, or throws InterruptedException if
555       * interrupted while waiting.
556       * @param phase the phase on entry to this method
557       * @return the phase on exit from this method
558       * @throws InterruptedException if thread interrupted while waiting
559       */
560 <    public int awaitAdvanceInterruptibly(int phase) throws InterruptedException {
560 >    public int awaitAdvanceInterruptibly(int phase)
561 >        throws InterruptedException {
562          if (phase < 0)
563              return phase;
564          long s = getReconciledState();
565          int p = phaseOf(s);
566          if (p != phase)
567              return p;
568 <        if (unarrivedOf(s) != 0)
568 >        if (unarrivedOf(s) == 0 && parent != null)
569              parent.awaitAdvanceInterruptibly(phase);
570          return interruptibleWait(phase);
571      }
# Line 577 | Line 587 | public class Phaser {
587          int p = phaseOf(s);
588          if (p != phase)
589              return p;
590 <        if (unarrivedOf(s) == 0)
590 >        if (unarrivedOf(s) == 0 && parent != null)
591              parent.awaitAdvanceInterruptibly(phase, timeout, unit);
592          return timedWait(phase, unit.toNanos(timeout));
593      }
# Line 608 | Line 618 | public class Phaser {
618  
619      /**
620       * Returns the current phase number. The maximum phase number is
621 <     * <tt>Integer.MAX_VALUE</tt>, after which it restarts at
621 >     * {@code Integer.MAX_VALUE}, after which it restarts at
622       * zero. Upon termination, the phase number is negative.
623       * @return the phase number, or a negative value if terminated
624       */
# Line 617 | Line 627 | public class Phaser {
627      }
628  
629      /**
630 <     * Returns true if the current phase number equals the given phase.
630 >     * Returns {@code true} if the current phase number equals the given phase.
631       * @param phase the phase
632 <     * @return true if the current phase number equals the given phase.
632 >     * @return {@code true} if the current phase number equals the given phase
633       */
634      public final boolean hasPhase(int phase) {
635          return phaseOf(getReconciledState()) == phase;
# Line 653 | Line 663 | public class Phaser {
663  
664      /**
665       * Returns the parent of this phaser, or null if none.
666 <     * @return the parent of this phaser, or null if none.
666 >     * @return the parent of this phaser, or null if none
667       */
668      public Phaser getParent() {
669          return parent;
# Line 662 | Line 672 | public class Phaser {
672      /**
673       * Returns the root ancestor of this phaser, which is the same as
674       * this phaser if it has no parent.
675 <     * @return the root ancestor of this phaser.
675 >     * @return the root ancestor of this phaser
676       */
677      public Phaser getRoot() {
678          return root;
679      }
680  
681      /**
682 <     * Returns true if this barrier has been terminated.
683 <     * @return true if this barrier has been terminated
682 >     * Returns {@code true} if this barrier has been terminated.
683 >     * @return {@code true} if this barrier has been terminated
684       */
685      public boolean isTerminated() {
686          return getPhase() < 0;
# Line 682 | Line 692 | public class Phaser {
692       * barrier is tripped (and thus all other waiting parties are
693       * dormant). If it returns true, then, rather than advance the
694       * phase number, this barrier will be set to a final termination
695 <     * state, and subsequent calls to <tt>isTerminated</tt> will
695 >     * state, and subsequent calls to {@code isTerminated} will
696       * return true.
697       *
698       * <p> The default version returns true when the number of
# Line 693 | Line 703 | public class Phaser {
703       * <p> You may override this method to perform an action with side
704       * effects visible to participating tasks, but it is in general
705       * only sensible to do so in designs where all parties register
706 <     * before any arrive, and all <tt>awaitAdvance</tt> at each phase.
706 >     * before any arrive, and all {@code awaitAdvance} at each phase.
707       * Otherwise, you cannot ensure lack of interference. In
708       * particular, this method may be invoked more than once per
709       * transition if other parties successfully register while the
# Line 702 | Line 712 | public class Phaser {
712       * method.
713       *
714       * @param phase the phase number on entering the barrier
715 <     * @param registeredParties the current number of registered
716 <     * parties.
707 <     * @return true if this barrier should terminate
715 >     * @param registeredParties the current number of registered parties
716 >     * @return {@code true} if this barrier should terminate
717       */
718      protected boolean onAdvance(int phase, int registeredParties) {
719          return registeredParties <= 0;
# Line 713 | Line 722 | public class Phaser {
722      /**
723       * Returns a string identifying this phaser, as well as its
724       * state.  The state, in brackets, includes the String {@code
725 <     * "phase ="} followed by the phase number, {@code "parties ="}
725 >     * "phase = "} followed by the phase number, {@code "parties = "}
726       * followed by the number of registered parties, and {@code
727 <     * "arrived ="} followed by the number of arrived parties
727 >     * "arrived = "} followed by the number of arrived parties.
728       *
729       * @return a string identifying this barrier, as well as its state
730       */
731      public String toString() {
732          long s = getReconciledState();
733 <        return super.toString() + "[phase = " + phaseOf(s) + " parties = " + partiesOf(s) + " arrived = " + arrivedOf(s) + "]";
733 >        return super.toString() +
734 >            "[phase = " + phaseOf(s) +
735 >            " parties = " + partiesOf(s) +
736 >            " arrived = " + arrivedOf(s) + "]";
737      }
738  
739      // methods for waiting
740  
729    /** The number of CPUs, for spin control */
730    static final int NCPUS = Runtime.getRuntime().availableProcessors();
731
732    /**
733     * The number of times to spin before blocking in timed waits.
734     * The value is empirically derived.
735     */
736    static final int maxTimedSpins = (NCPUS < 2)? 0 : 32;
737
738    /**
739     * The number of times to spin before blocking in untimed waits.
740     * This is greater than timed value because untimed waits spin
741     * faster since they don't need to check times on each spin.
742     */
743    static final int maxUntimedSpins = maxTimedSpins * 32;
744
741      /**
742 <     * The number of nanoseconds for which it is faster to spin
747 <     * rather than to use timed park. A rough estimate suffices.
742 >     * Wait nodes for Treiber stack representing wait queue
743       */
744 <    static final long spinForTimeoutThreshold = 1000L;
745 <
746 <    /**
747 <     * Wait nodes for Treiber stack representing wait queue for non-FJ
748 <     * tasks.
749 <     */
750 <    static final class QNode {
751 <        QNode next;
744 >    static final class QNode implements ForkJoinPool.ManagedBlocker {
745 >        final Phaser phaser;
746 >        final int phase;
747 >        final long startTime;
748 >        final long nanos;
749 >        final boolean timed;
750 >        final boolean interruptible;
751 >        volatile boolean wasInterrupted = false;
752          volatile Thread thread; // nulled to cancel wait
753 <        QNode() {
753 >        QNode next;
754 >        QNode(Phaser phaser, int phase, boolean interruptible,
755 >              boolean timed, long startTime, long nanos) {
756 >            this.phaser = phaser;
757 >            this.phase = phase;
758 >            this.timed = timed;
759 >            this.interruptible = interruptible;
760 >            this.startTime = startTime;
761 >            this.nanos = nanos;
762              thread = Thread.currentThread();
763          }
764 +        public boolean isReleasable() {
765 +            return (thread == null ||
766 +                    phaser.getPhase() != phase ||
767 +                    (interruptible && wasInterrupted) ||
768 +                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
769 +        }
770 +        public boolean block() {
771 +            if (Thread.interrupted()) {
772 +                wasInterrupted = true;
773 +                if (interruptible)
774 +                    return true;
775 +            }
776 +            if (!timed)
777 +                LockSupport.park(this);
778 +            else {
779 +                long waitTime = nanos - (System.nanoTime() - startTime);
780 +                if (waitTime <= 0)
781 +                    return true;
782 +                LockSupport.parkNanos(this, waitTime);
783 +            }
784 +            return isReleasable();
785 +        }
786          void signal() {
787              Thread t = thread;
788              if (t != null) {
# Line 765 | Line 790 | public class Phaser {
790                  LockSupport.unpark(t);
791              }
792          }
793 +        boolean doWait() {
794 +            if (thread != null) {
795 +                try {
796 +                    ForkJoinPool.managedBlock(this, false);
797 +                } catch (InterruptedException ie) {
798 +                }
799 +            }
800 +            return wasInterrupted;
801 +        }
802 +
803      }
804  
805      /**
# Line 780 | Line 815 | public class Phaser {
815      }
816  
817      /**
818 +     * Tries to enqueue given node in the appropriate wait queue
819 +     * @return true if successful
820 +     */
821 +    private boolean tryEnqueue(QNode node) {
822 +        AtomicReference<QNode> head = queueFor(node.phase);
823 +        return head.compareAndSet(node.next = head.get(), node);
824 +    }
825 +
826 +    /**
827       * Enqueues node and waits unless aborted or signalled.
828 +     * @return current phase
829       */
830      private int untimedWait(int phase) {
786        int spins = maxUntimedSpins;
831          QNode node = null;
788        boolean interrupted = false;
832          boolean queued = false;
833 +        boolean interrupted = false;
834          int p;
835          while ((p = getPhase()) == phase) {
836 <            interrupted = Thread.interrupted();
837 <            if (node != null) {
838 <                if (!queued) {
839 <                    AtomicReference<QNode> head = queueFor(phase);
840 <                    queued = head.compareAndSet(node.next = head.get(), node);
841 <                }
798 <                else if (node.thread != null)
799 <                    LockSupport.park(this);
800 <            }
801 <            else if (spins <= 0)
802 <                node = new QNode();
836 >            if (Thread.interrupted())
837 >                interrupted = true;
838 >            else if (node == null)
839 >                node = new QNode(this, phase, false, false, 0, 0);
840 >            else if (!queued)
841 >                queued = tryEnqueue(node);
842              else
843 <                --spins;
843 >                interrupted = node.doWait();
844          }
845          if (node != null)
846              node.thread = null;
847 +        releaseWaiters(phase);
848          if (interrupted)
849              Thread.currentThread().interrupt();
810        releaseWaiters(phase);
850          return p;
851      }
852  
853      /**
854 <     * Messier interruptible version
854 >     * Interruptible version
855 >     * @return current phase
856       */
857      private int interruptibleWait(int phase) throws InterruptedException {
818        int spins = maxUntimedSpins;
858          QNode node = null;
859          boolean queued = false;
860          boolean interrupted = false;
861          int p;
862 <        while ((p = getPhase()) == phase) {
863 <            if (interrupted = Thread.interrupted())
864 <                break;
865 <            if (node != null) {
866 <                if (!queued) {
867 <                    AtomicReference<QNode> head = queueFor(phase);
868 <                    queued = head.compareAndSet(node.next = head.get(), node);
830 <                }
831 <                else if (node.thread != null)
832 <                    LockSupport.park(this);
833 <            }
834 <            else if (spins <= 0)
835 <                node = new QNode();
862 >        while ((p = getPhase()) == phase && !interrupted) {
863 >            if (Thread.interrupted())
864 >                interrupted = true;
865 >            else if (node == null)
866 >                node = new QNode(this, phase, true, false, 0, 0);
867 >            else if (!queued)
868 >                queued = tryEnqueue(node);
869              else
870 <                --spins;
870 >                interrupted = node.doWait();
871          }
872          if (node != null)
873              node.thread = null;
874 +        if (p != phase || (p = getPhase()) != phase)
875 +            releaseWaiters(phase);
876          if (interrupted)
877              throw new InterruptedException();
843        releaseWaiters(phase);
878          return p;
879      }
880  
881      /**
882 <     * Even messier timeout version.
882 >     * Timeout version.
883 >     * @return current phase
884       */
885      private int timedWait(int phase, long nanos)
886          throws InterruptedException, TimeoutException {
887 +        long startTime = System.nanoTime();
888 +        QNode node = null;
889 +        boolean queued = false;
890 +        boolean interrupted = false;
891          int p;
892 <        if ((p = getPhase()) == phase) {
893 <            long lastTime = System.nanoTime();
894 <            int spins = maxTimedSpins;
895 <            QNode node = null;
896 <            boolean queued = false;
897 <            boolean interrupted = false;
898 <            while ((p = getPhase()) == phase) {
899 <                if (interrupted = Thread.interrupted())
900 <                    break;
901 <                long now = System.nanoTime();
902 <                if ((nanos -= now - lastTime) <= 0)
864 <                    break;
865 <                lastTime = now;
866 <                if (node != null) {
867 <                    if (!queued) {
868 <                        AtomicReference<QNode> head = queueFor(phase);
869 <                        queued = head.compareAndSet(node.next = head.get(), node);
870 <                    }
871 <                    else if (node.thread != null &&
872 <                             nanos > spinForTimeoutThreshold) {
873 <                        LockSupport.parkNanos(this, nanos);
874 <                    }
875 <                }
876 <                else if (spins <= 0)
877 <                    node = new QNode();
878 <                else
879 <                    --spins;
880 <            }
881 <            if (node != null)
882 <                node.thread = null;
883 <            if (interrupted)
884 <                throw new InterruptedException();
885 <            if (p == phase && (p = getPhase()) == phase)
886 <                throw new TimeoutException();
892 >        while ((p = getPhase()) == phase && !interrupted) {
893 >            if (Thread.interrupted())
894 >                interrupted = true;
895 >            else if (nanos - (System.nanoTime() - startTime) <= 0)
896 >                break;
897 >            else if (node == null)
898 >                node = new QNode(this, phase, true, true, startTime, nanos);
899 >            else if (!queued)
900 >                queued = tryEnqueue(node);
901 >            else
902 >                interrupted = node.doWait();
903          }
904 <        releaseWaiters(phase);
904 >        if (node != null)
905 >            node.thread = null;
906 >        if (p != phase || (p = getPhase()) != phase)
907 >            releaseWaiters(phase);
908 >        if (interrupted)
909 >            throw new InterruptedException();
910 >        if (p == phase)
911 >            throw new TimeoutException();
912          return p;
913      }
914  
915      // Temporary Unsafe mechanics for preliminary release
916 +    private static Unsafe getUnsafe() throws Throwable {
917 +        try {
918 +            return Unsafe.getUnsafe();
919 +        } catch (SecurityException se) {
920 +            try {
921 +                return java.security.AccessController.doPrivileged
922 +                    (new java.security.PrivilegedExceptionAction<Unsafe>() {
923 +                        public Unsafe run() throws Exception {
924 +                            return getUnsafePrivileged();
925 +                        }});
926 +            } catch (java.security.PrivilegedActionException e) {
927 +                throw e.getCause();
928 +            }
929 +        }
930 +    }
931 +
932 +    private static Unsafe getUnsafePrivileged()
933 +            throws NoSuchFieldException, IllegalAccessException {
934 +        Field f = Unsafe.class.getDeclaredField("theUnsafe");
935 +        f.setAccessible(true);
936 +        return (Unsafe)f.get(null);
937 +    }
938 +
939 +    private static long fieldOffset(String fieldName)
940 +            throws NoSuchFieldException {
941 +        return _unsafe.objectFieldOffset
942 +            (Phaser.class.getDeclaredField(fieldName));
943 +    }
944  
945      static final Unsafe _unsafe;
946      static final long stateOffset;
947  
948      static {
949          try {
950 <            if (Phaser.class.getClassLoader() != null) {
951 <                Field f = Unsafe.class.getDeclaredField("theUnsafe");
901 <                f.setAccessible(true);
902 <                _unsafe = (Unsafe)f.get(null);
903 <            }
904 <            else
905 <                _unsafe = Unsafe.getUnsafe();
906 <            stateOffset = _unsafe.objectFieldOffset
907 <                (Phaser.class.getDeclaredField("state"));
950 >            _unsafe = getUnsafe();
951 >            stateOffset = fieldOffset("state");
952          } catch (Exception e) {
953              throw new RuntimeException("Could not initialize intrinsics", e);
954          }

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines