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.64 by jsr166, Mon Nov 29 20:58:06 2010 UTC vs.
Revision 1.65 by dl, Wed Dec 1 17:20:41 2010 UTC

# Line 183 | Line 183 | import java.util.concurrent.locks.LockSu
183   * }}</pre>
184   *
185   *
186 < * <p>To create a set of tasks using a tree of phasers,
187 < * you could use code of the following form, assuming a
188 < * Task class with a constructor accepting a {@code Phaser} that
189 < * it registers with upon construction:
186 > * <p>To create a set of {@code n} tasks using a tree of phasers, you
187 > * could use code of the following form, assuming a Task class with a
188 > * constructor accepting a {@code Phaser} that it registers with upon
189 > * construction. After invocation of {@code build(new Task[n], 0, n,
190 > * new Phaser())}, these tasks could then be started, for example by
191 > * submitting to a pool:
192   *
193   *  <pre> {@code
194 < * void build(Task[] actions, int lo, int hi, Phaser ph) {
194 > * void build(Task[] tasks, int lo, int hi, Phaser ph) {
195   *   if (hi - lo > TASKS_PER_PHASER) {
196   *     for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
197   *       int j = Math.min(i + TASKS_PER_PHASER, hi);
198 < *       build(actions, i, j, new Phaser(ph));
198 > *       build(tasks, i, j, new Phaser(ph));
199   *     }
200   *   } else {
201   *     for (int i = lo; i < hi; ++i)
202 < *       actions[i] = new Task(ph);
202 > *       tasks[i] = new Task(ph);
203   *       // assumes new Task(ph) performs ph.register()
204   *   }
205 < * }
204 < * // .. initially called, for n tasks via
205 < * build(new Task[n], 0, n, new Phaser());}</pre>
205 > * }}</pre>
206   *
207   * The best value of {@code TASKS_PER_PHASER} depends mainly on
208   * expected synchronization rates. A value as low as four may
# Line 233 | Line 233 | public class Phaser {
233       * * phase -- the generation of the barrier                (bits 32-62)
234       * * terminated -- set if barrier is terminated            (bit  63 / sign)
235       *
236 <     * However, to efficiently maintain atomicity, these values are
237 <     * packed into a single (atomic) long. Termination uses the sign
238 <     * bit of 32 bit representation of phase, so phase is set to -1 on
239 <     * termination. Good performance relies on keeping state decoding
240 <     * and encoding simple, and keeping race windows short.
236 >     * Except that a phaser with no registered parties is
237 >     * distinguished with the otherwise illegal state of having zero
238 >     * parties and one unarrived parties (encoded as EMPTY below).
239 >     *
240 >     * To efficiently maintain atomicity, these values are packed into
241 >     * a single (atomic) long. Good performance relies on keeping
242 >     * state decoding and encoding simple, and keeping race windows
243 >     * short.
244 >     *
245 >     * All state updates are performed via CAS except initial
246 >     * registration of a sub-phaser (i.e., one with a non-null
247 >     * parent).  In this (relatively rare) case, we use built-in
248 >     * synchronization to lock while first registering with its
249 >     * parent.
250 >     *
251 >     * The phase of a subphaser is allowed to lag that of its
252 >     * ancestors until it is actually accessed.  Method reconcileState
253 >     * is usually attempted only only when the number of unarrived
254 >     * parties appears to be zero, which indicates a potential lag in
255 >     * updating phase after the root advanced.
256       */
257      private volatile long state;
258  
# Line 247 | Line 262 | public class Phaser {
262      private static final int  PHASE_SHIFT     = 32;
263      private static final int  UNARRIVED_MASK  = 0xffff;      // to mask ints
264      private static final long PARTIES_MASK    = 0xffff0000L; // to mask longs
250    private static final long ONE_ARRIVAL     = 1L;
251    private static final long ONE_PARTY       = 1L << PARTIES_SHIFT;
265      private static final long TERMINATION_BIT = 1L << 63;
266  
267 +    // some special values
268 +    private static final int  ONE_ARRIVAL     = 1;
269 +    private static final int  ONE_PARTY       = 1 << PARTIES_SHIFT;
270 +    private static final int  EMPTY           = 1;
271 +
272      // The following unpacking methods are usually manually inlined
273  
274      private static int unarrivedOf(long s) {
275 <        return (int)s & UNARRIVED_MASK;
275 >        int counts = (int)s;
276 >        return (counts == EMPTY)? 0 : counts & UNARRIVED_MASK;
277      }
278  
279      private static int partiesOf(long s) {
280 <        return (int)s >>> PARTIES_SHIFT;
280 >        int counts = (int)s;
281 >        return (counts == EMPTY)? 0 : counts >>> PARTIES_SHIFT;
282      }
283  
284      private static int phaseOf(long s) {
# Line 266 | Line 286 | public class Phaser {
286      }
287  
288      private static int arrivedOf(long s) {
289 <        return partiesOf(s) - unarrivedOf(s);
289 >        int counts = (int)s;
290 >        return (counts == EMPTY)? 0 :
291 >            (counts >>> PARTIES_SHIFT) - (counts & UNARRIVED_MASK);
292      }
293  
294      /**
# Line 275 | Line 297 | public class Phaser {
297      private final Phaser parent;
298  
299      /**
300 <     * The root of phaser tree. Equals this if not in a tree.  Used to
279 <     * support faster state push-down.
300 >     * The root of phaser tree. Equals this if not in a tree.
301       */
302      private final Phaser root;
303  
# Line 314 | Line 335 | public class Phaser {
335       * Manually tuned to speed up and minimize race windows for the
336       * common case of just decrementing unarrived field.
337       *
338 <     * @param adj - adjustment to apply to state -- either
318 <     * ONE_ARRIVAL (for arrive) or
319 <     * ONE_ARRIVAL|ONE_PARTY (for arriveAndDeregister)
338 >     * @param deregister false for arrive, true for arriveAndDeregister
339       */
340 <    private int doArrive(long adj) {
341 <        for (;;) {
342 <            long s = state;
343 <            int unarrived = (int)s & UNARRIVED_MASK;
344 <            int phase = (int)(s >>> PHASE_SHIFT);
345 <            if (phase < 0)
346 <                return phase;
347 <            else if (unarrived == 0) {
348 <                if (reconcileState() == s)     // recheck
340 >    private int doArrive(boolean deregister) {
341 >        int adj = deregister ? ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL;
342 >        long s;
343 >        int phase;
344 >        while ((phase = (int)((s = state) >>> PHASE_SHIFT)) >= 0) {
345 >            int counts = (int)s;
346 >            int unarrived = counts & UNARRIVED_MASK;
347 >            if (counts == EMPTY || unarrived == 0) {
348 >                if (reconcileState() == s)
349                      throw new IllegalStateException(badArrive(s));
350              }
351              else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) {
352                  if (unarrived == 1) {
353 <                    long p = s & PARTIES_MASK; // unshifted parties field
354 <                    long lu = p >>> PARTIES_SHIFT;
355 <                    int u = (int)lu;
356 <                    int nextPhase = (phase + 1) & MAX_PHASE;
357 <                    long next = ((long)nextPhase << PHASE_SHIFT) | p | lu;
358 <                    final Phaser parent = this.parent;
340 <                    if (parent == null) {
341 <                        if (onAdvance(phase, u))
342 <                            next |= TERMINATION_BIT;
343 <                        UNSAFE.compareAndSwapLong(this, stateOffset, s, next);
344 <                        releaseWaiters(phase);
353 >                    long n = s & PARTIES_MASK;       // unshifted parties field
354 >                    int u = ((int)n) >>> PARTIES_SHIFT;
355 >                    Phaser par = parent;
356 >                    if (par != null) {
357 >                        par.doArrive(u == 0);
358 >                        reconcileState();
359                      }
360                      else {
361 <                        parent.doArrive((u == 0) ?
362 <                                        ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL);
363 <                        if ((int)(parent.state >>> PHASE_SHIFT) != nextPhase)
364 <                            reconcileState();
365 <                        else if (state == s)
366 <                            UNSAFE.compareAndSwapLong(this, stateOffset, s,
367 <                                                      next);
361 >                        n |= (((long)((phase+1) & MAX_PHASE)) << PHASE_SHIFT);
362 >                        if (onAdvance(phase, u))
363 >                            n |= TERMINATION_BIT;
364 >                        else if (u == 0)
365 >                            n |= EMPTY;             // reset to unregistered
366 >                        else
367 >                            n |= (long)u;           // reset unarr to parties
368 >                        // assert state == s || isTerminated();
369 >                        UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
370 >                        releaseWaiters(phase);
371                      }
372                  }
373 <                return phase;
373 >                break;
374              }
375          }
376 +        return phase;
377      }
378  
379      /**
# Line 367 | Line 385 | public class Phaser {
385      private int doRegister(int registrations) {
386          // adjustment to state
387          long adj = ((long)registrations << PARTIES_SHIFT) | registrations;
388 <        final Phaser parent = this.parent;
388 >        Phaser par = parent;
389 >        int phase;
390          for (;;) {
391 <            long s = (parent == null) ? state : reconcileState();
392 <            int parties = (int)s >>> PARTIES_SHIFT;
393 <            int phase = (int)(s >>> PHASE_SHIFT);
394 <            if (phase < 0)
395 <                return phase;
377 <            else if (registrations > MAX_PARTIES - parties)
391 >            long s = state;
392 >            int counts = (int)s;
393 >            int parties = counts >>> PARTIES_SHIFT;
394 >            int unarrived = counts & UNARRIVED_MASK;
395 >            if (registrations > MAX_PARTIES - parties)
396                  throw new IllegalStateException(badRegister(s));
397 <            else if ((parties == 0 && parent == null) || // first reg of root
398 <                     ((int)s & UNARRIVED_MASK) != 0) {   // not advancing
399 <                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s + adj))
400 <                    return phase;
401 <            }
402 <            else if (parties != 0)               // wait for onAdvance
403 <                root.internalAwaitAdvance(phase, null);
404 <            else {                               // 1st registration of child
405 <                synchronized (this) {            // register parent first
406 <                    if (reconcileState() == s) { // recheck under lock
407 <                        parent.doRegister(1);    // OK if throws IllegalState
408 <                        for (;;) {               // simpler form of outer loop
409 <                            s = reconcileState();
410 <                            phase = (int)(s >>> PHASE_SHIFT);
411 <                            if (phase < 0 ||
412 <                                UNSAFE.compareAndSwapLong(this, stateOffset,
413 <                                                          s, s + adj))
414 <                                return phase;
415 <                        }
397 >            else if ((phase = (int)(s >>> PHASE_SHIFT)) < 0)
398 >                break;
399 >            else if (counts != EMPTY) {             // not 1st registration
400 >                if (par == null || reconcileState() == s) {
401 >                    if (unarrived == 0)             // wait out advance
402 >                        root.internalAwaitAdvance(phase, null);
403 >                    else if (UNSAFE.compareAndSwapLong(this, stateOffset,
404 >                                                       s, s + adj))
405 >                        break;
406 >                }
407 >            }
408 >            else if (par == null) {                 // 1st root registration
409 >                long next = (((long) phase) << PHASE_SHIFT) | adj;
410 >                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
411 >                    break;
412 >            }
413 >            else {
414 >                synchronized(this) {                // 1st sub registration
415 >                    if (state == s) {               // recheck under lock
416 >                        par.doRegister(1);
417 >                        do {                        // force current phase
418 >                            phase = (int)(root.state >>> PHASE_SHIFT);
419 >                            // assert phase < 0 || (int)state == EMPTY;
420 >                        } while (!UNSAFE.compareAndSwapLong
421 >                                 (this, stateOffset, state,
422 >                                  (((long) phase) << PHASE_SHIFT) | adj));
423 >                        break;
424                      }
425                  }
426              }
427          }
428 +        return phase;
429      }
430  
431      /**
432 <     * Recursively resolves lagged phase propagation from root if necessary.
432 >     * Resolves lagged phase propagation from root if necessary.
433       */
434      private long reconcileState() {
435 <        Phaser par = parent;
435 >        Phaser rt = root;
436          long s = state;
437 <        if (par != null) {
438 <            Phaser rt = root;
439 <            int phase, rPhase;
440 <            while ((phase = (int)(s >>> PHASE_SHIFT)) >= 0 &&
441 <                   (rPhase = (int)(rt.state >>> PHASE_SHIFT)) != phase) {
442 <                if (par != rt && (int)(par.state >>> PHASE_SHIFT) != rPhase)
443 <                    par.reconcileState();
444 <                else if (rPhase < 0 || ((int)s & UNARRIVED_MASK) == 0) {
445 <                    long u = s & PARTIES_MASK; // reset unarrived to parties
446 <                    long next = ((((long) rPhase) << PHASE_SHIFT) | u |
447 <                                 (u >>> PARTIES_SHIFT));
448 <                    UNSAFE.compareAndSwapLong(this, stateOffset, s, next);
437 >        if (rt != this) {
438 >            int phase;
439 >            while ((phase = (int)(rt.state >>> PHASE_SHIFT)) !=
440 >                   (int)(s >>> PHASE_SHIFT)) {
441 >                // assert phase < 0 || unarrivedOf(s) == 0
442 >                long t;                             // to reread s
443 >                long p = s & PARTIES_MASK;          // unshifted parties field
444 >                long n = (((long) phase) << PHASE_SHIFT) | p;
445 >                if (phase >= 0) {
446 >                    if (p == 0L)
447 >                        n |= EMPTY;                 // reset to empty
448 >                    else
449 >                        n |= p >>> PARTIES_SHIFT;   // set unarr to parties
450                  }
451 <                s = state;
451 >                if ((t = state) == s &&
452 >                    UNSAFE.compareAndSwapLong(this, stateOffset, s, s = n))
453 >                    break;
454 >                s = t;
455              }
456          }
457          return s;
# Line 478 | Line 509 | public class Phaser {
509      public Phaser(Phaser parent, int parties) {
510          if (parties >>> PARTIES_SHIFT != 0)
511              throw new IllegalArgumentException("Illegal number of parties");
512 <        long s = ((long) parties) | (((long) parties) << PARTIES_SHIFT);
512 >        int phase = 0;
513          this.parent = parent;
514          if (parent != null) {
515              Phaser r = parent.root;
# Line 486 | Line 517 | public class Phaser {
517              this.evenQ = r.evenQ;
518              this.oddQ = r.oddQ;
519              if (parties != 0)
520 <                s |= ((long)(parent.doRegister(1))) << PHASE_SHIFT;
520 >                phase = parent.doRegister(1);
521          }
522          else {
523              this.root = this;
524              this.evenQ = new AtomicReference<QNode>();
525              this.oddQ = new AtomicReference<QNode>();
526          }
527 <        this.state = s;
527 >        this.state = (parties == 0)? ((long) EMPTY) :
528 >            ((((long) phase) << PHASE_SHIFT) |
529 >             (((long) parties) << PARTIES_SHIFT) |
530 >             ((long) parties));
531      }
532  
533      /**
# Line 547 | Line 581 | public class Phaser {
581       * of unarrived parties would become negative
582       */
583      public int arrive() {
584 <        return doArrive(ONE_ARRIVAL);
584 >        return doArrive(false);
585      }
586  
587      /**
# Line 567 | Line 601 | public class Phaser {
601       * of registered or unarrived parties would become negative
602       */
603      public int arriveAndDeregister() {
604 <        return doArrive(ONE_ARRIVAL|ONE_PARTY);
604 >        return doArrive(true);
605      }
606  
607      /**
# Line 588 | Line 622 | public class Phaser {
622       * of unarrived parties would become negative
623       */
624      public int arriveAndAwaitAdvance() {
625 <        return awaitAdvance(doArrive(ONE_ARRIVAL));
625 >        return awaitAdvance(doArrive(false));
626      }
627  
628      /**
# Line 607 | Line 641 | public class Phaser {
641          int p = (int)(state >>> PHASE_SHIFT);
642          if (phase < 0)
643              return phase;
644 <        if (p == phase &&
645 <            (p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase)
646 <            return rt.internalAwaitAdvance(phase, null);
644 >        if (p == phase) {
645 >            if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase)
646 >                return rt.internalAwaitAdvance(phase, null);
647 >            reconcileState();
648 >        }
649          return p;
650      }
651  
# Line 633 | Line 669 | public class Phaser {
669          int p = (int)(state >>> PHASE_SHIFT);
670          if (phase < 0)
671              return phase;
672 <        if (p == phase &&
673 <            (p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
674 <            QNode node = new QNode(this, phase, true, false, 0L);
675 <            p = rt.internalAwaitAdvance(phase, node);
676 <            if (node.wasInterrupted)
677 <                throw new InterruptedException();
672 >        if (p == phase) {
673 >            if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
674 >                QNode node = new QNode(this, phase, true, false, 0L);
675 >                p = rt.internalAwaitAdvance(phase, node);
676 >                if (node.wasInterrupted)
677 >                    throw new InterruptedException();
678 >            }
679 >            else
680 >                reconcileState();
681          }
682          return p;
683      }
# Line 670 | Line 709 | public class Phaser {
709          int p = (int)(state >>> PHASE_SHIFT);
710          if (phase < 0)
711              return phase;
712 <        if (p == phase &&
713 <            (p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
714 <            QNode node = new QNode(this, phase, true, true, nanos);
715 <            p = rt.internalAwaitAdvance(phase, node);
716 <            if (node.wasInterrupted)
717 <                throw new InterruptedException();
718 <            else if (p == phase)
719 <                throw new TimeoutException();
712 >        if (p == phase) {
713 >            if ((p = (int)((rt = root).state >>> PHASE_SHIFT)) == phase) {
714 >                QNode node = new QNode(this, phase, true, true, nanos);
715 >                p = rt.internalAwaitAdvance(phase, node);
716 >                if (node.wasInterrupted)
717 >                    throw new InterruptedException();
718 >                else if (p == phase)
719 >                    throw new TimeoutException();
720 >            }
721 >            else
722 >                reconcileState();
723          }
724          return p;
725      }
726  
727      /**
728       * Forces this phaser to enter termination state.  Counts of
729 <     * arrived and registered parties are unaffected.  If this phaser
730 <     * is a member of a tiered set of phasers, then all of the phasers
731 <     * in the set are terminated.  If this phaser is already
732 <     * terminated, this method has no effect.  This method may be
733 <     * useful for coordinating recovery after one or more tasks
734 <     * encounter unexpected exceptions.
729 >     * registered parties are unaffected.  If this phaser is a member
730 >     * of a tiered set of phasers, then all of the phasers in the set
731 >     * are terminated.  If this phaser is already terminated, this
732 >     * method has no effect.  This method may be useful for
733 >     * coordinating recovery after one or more tasks encounter
734 >     * unexpected exceptions.
735       */
736      public void forceTermination() {
737          // Only need to change root state
738          final Phaser root = this.root;
739          long s;
740          while ((s = root.state) >= 0) {
741 <            if (UNSAFE.compareAndSwapLong(root, stateOffset,
742 <                                          s, s | TERMINATION_BIT)) {
741 >            long next = (s & ~(long)(MAX_PARTIES)) | TERMINATION_BIT;
742 >            if (UNSAFE.compareAndSwapLong(root, stateOffset, s, next)) {
743                  releaseWaiters(0); // signal all threads
744                  releaseWaiters(1);
745                  return;
# Line 734 | Line 776 | public class Phaser {
776       * @return the number of arrived parties
777       */
778      public int getArrivedParties() {
779 <        long s = state;
738 <        int u = unarrivedOf(s); // only reconcile if possibly needed
739 <        return (u != 0 || parent == null) ?
740 <            partiesOf(s) - u :
741 <            arrivedOf(reconcileState());
779 >        return arrivedOf(reconcileState());
780      }
781  
782      /**
# Line 748 | Line 786 | public class Phaser {
786       * @return the number of unarrived parties
787       */
788      public int getUnarrivedParties() {
789 <        int u = unarrivedOf(state);
752 <        return (u != 0 || parent == null) ? u : unarrivedOf(reconcileState());
789 >        return unarrivedOf(reconcileState());
790      }
791  
792      /**
# Line 785 | Line 822 | public class Phaser {
822       * advance, and to control termination. This method is invoked
823       * upon arrival of the party advancing this phaser (when all other
824       * waiting parties are dormant).  If this method returns {@code
825 <     * true}, then, rather than advance the phase number, this phaser
826 <     * will be set to a final termination state, and subsequent calls
827 <     * to {@link #isTerminated} will return true. Any (unchecked)
828 <     * Exception or Error thrown by an invocation of this method is
829 <     * propagated to the party attempting to advance this phaser, in
830 <     * which case no advance occurs.
825 >     * true}, this phaser will be set to a final termination state
826 >     * upon advance, and subsequent calls to {@link #isTerminated}
827 >     * will return true. Any (unchecked) Exception or Error thrown by
828 >     * an invocation of this method is propagated to the party
829 >     * attempting to advance this phaser, in which case no advance
830 >     * occurs.
831       *
832       * <p>The arguments to this method provide the state of the phaser
833       * prevailing for the current transition.  The effects of invoking
# Line 856 | Line 893 | public class Phaser {
893          QNode q;   // first element of queue
894          int p;     // its phase
895          Thread t;  // its thread
896 +        //        assert phase != phaseOf(root.state);
897          AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
898          while ((q = head.get()) != null &&
899 <               ((p = q.phase) == phase ||
862 <                (int)(root.state >>> PHASE_SHIFT) != p)) {
899 >               q.phase != (int)(root.state >>> PHASE_SHIFT)) {
900              if (head.compareAndSet(q, q.next) &&
901                  (t = q.thread) != null) {
902                  q.thread = null;
# Line 935 | Line 972 | public class Phaser {
972                  node.thread = null;       // avoid need for unpark()
973              if (node.wasInterrupted && !node.interruptible)
974                  Thread.currentThread().interrupt();
975 <            if ((p = (int)(state >>> PHASE_SHIFT)) == phase)
975 >            if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
976                  return p;                 // recheck abort
977          }
978          releaseWaiters(phase);

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines