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.44 by dl, Tue Aug 25 16:32:28 2009 UTC vs.
Revision 1.49 by dl, Fri Nov 5 23:01:47 2010 UTC

# Line 7 | Line 7
7   package jsr166y;
8  
9   import java.util.concurrent.*;
10
10   import java.util.concurrent.atomic.AtomicReference;
11   import java.util.concurrent.locks.LockSupport;
12  
# Line 109 | Line 108 | import java.util.concurrent.locks.LockSu
108   * <p><b>Sample usages:</b>
109   *
110   * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
111 < * to control a one-shot action serving a variable number of
112 < * parties. The typical idiom is for the method setting this up to
113 < * first register, then start the actions, then deregister, as in:
111 > * to control a one-shot action serving a variable number of parties.
112 > * The typical idiom is for the method setting this up to first
113 > * register, then start the actions, then deregister, as in:
114   *
115   *  <pre> {@code
116   * void runTasks(List<Runnable> tasks) {
# Line 142 | Line 141 | import java.util.concurrent.locks.LockSu
141   *     }
142   *   };
143   *   phaser.register();
144 < *   for (Runnable task : tasks) {
144 > *   for (final Runnable task : tasks) {
145   *     phaser.register();
146   *     new Thread() {
147   *       public void run() {
148   *         do {
149   *           task.run();
150   *           phaser.arriveAndAwaitAdvance();
151 < *         } while(!phaser.isTerminated();
151 > *         } while (!phaser.isTerminated());
152   *       }
153   *     }.start();
154   *   }
# Line 158 | Line 157 | import java.util.concurrent.locks.LockSu
157   *
158   * If the main task must later await termination, it
159   * may re-register and then execute a similar loop:
160 < * <pre> {@code
160 > *  <pre> {@code
161   *   // ...
162   *   phaser.register();
163   *   while (!phaser.isTerminated())
164 < *     phaser.arriveAndAwaitAdvance();
166 < * }</pre>
164 > *     phaser.arriveAndAwaitAdvance();}</pre>
165   *
166 < * Related constructions may be used to await particular phase numbers
166 > * <p>Related constructions may be used to await particular phase numbers
167   * in contexts where you are sure that the phase will never wrap around
168   * {@code Integer.MAX_VALUE}. For example:
169   *
170 < * <pre> {@code
171 < *   void awaitPhase(Phaser phaser, int phase) {
172 < *     int p = phaser.register(); // assumes caller not already registered
173 < *     while (p < phase) {
174 < *       if (phaser.isTerminated())
175 < *         // ... deal with unexpected termination
176 < *       else
177 < *         p = phaser.arriveAndAwaitAdvance();
180 < *     }
181 < *     phaser.arriveAndDeregister();
170 > *  <pre> {@code
171 > * void awaitPhase(Phaser phaser, int phase) {
172 > *   int p = phaser.register(); // assumes caller not already registered
173 > *   while (p < phase) {
174 > *     if (phaser.isTerminated())
175 > *       // ... deal with unexpected termination
176 > *     else
177 > *       p = phaser.arriveAndAwaitAdvance();
178   *   }
179 < * }</pre>
179 > *   phaser.arriveAndDeregister();
180 > * }}</pre>
181   *
182   *
183   * <p>To create a set of tasks using a tree of phasers,
184   * you could use code of the following form, assuming a
185   * Task class with a constructor accepting a phaser that
186 < * it registers for upon construction:
186 > * it registers with upon construction:
187 > *
188   *  <pre> {@code
189   * void build(Task[] actions, int lo, int hi, Phaser ph) {
190   *   if (hi - lo > TASKS_PER_PHASER) {
# Line 208 | Line 206 | import java.util.concurrent.locks.LockSu
206   * be appropriate for extremely small per-barrier task bodies (thus
207   * high rates), or up to hundreds for extremely large ones.
208   *
211 * </pre>
212 *
209   * <p><b>Implementation notes</b>: This implementation restricts the
210   * maximum number of parties to 65535. Attempts to register additional
211   * parties result in {@code IllegalStateException}. However, you can and
# Line 298 | Line 294 | public class Phaser {
294  
295      /**
296       * Heads of Treiber stacks for waiting threads. To eliminate
297 <     * contention while releasing some threads while adding others, we
297 >     * contention when releasing some threads while adding others, we
298       * use two of them, alternating across even and odd phases.
299 +     * Subphasers share queues with root to speed up releases.
300       */
301      private final AtomicReference<QNode> evenQ = new AtomicReference<QNode>();
302      private final AtomicReference<QNode> oddQ  = new AtomicReference<QNode>();
303  
304      private AtomicReference<QNode> queueFor(int phase) {
305 <        return ((phase & 1) == 0) ? evenQ : oddQ;
305 >        Phaser r = root;
306 >        return ((phase & 1) == 0) ? r.evenQ : r.oddQ;
307      }
308  
309      /**
# Line 320 | Line 318 | public class Phaser {
318       * Recursively resolves state.
319       */
320      private long reconcileState() {
321 <        Phaser p = parent;
321 >        Phaser par = parent;
322          long s = state;
323 <        if (p != null) {
324 <            while (unarrivedOf(s) == 0 && phaseOf(s) != phaseOf(root.state)) {
325 <                long parentState = p.getReconciledState();
323 >        if (par != null) {
324 >            int phase, rootPhase;
325 >            while ((phase = phaseOf(s)) >= 0 &&
326 >                   (rootPhase = phaseOf(root.state)) != phase &&
327 >                   (rootPhase < 0 || unarrivedOf(s) == 0)) {
328 >                long parentState = par.getReconciledState();
329                  int parentPhase = phaseOf(parentState);
330 <                int phase = phaseOf(s = state);
331 <                if (phase != parentPhase) {
332 <                    long next = trippedStateFor(parentPhase, partiesOf(s));
333 <                    if (casState(s, next)) {
334 <                        releaseWaiters(phase);
335 <                        s = next;
336 <                    }
330 >                int parties = partiesOf(s);
331 >                long next = trippedStateFor(parentPhase, parties);
332 >                if (phaseOf(root.state) == rootPhase &&
333 >                    parentPhase != phase &&
334 >                    state == s && casState(s, next)) {
335 >                    releaseWaiters(phase);
336 >                    if (parties == 0) // exit if the final deregistration
337 >                        break;
338                  }
339 +                s = state;
340              }
341          }
342          return s;
# Line 349 | Line 352 | public class Phaser {
352      }
353  
354      /**
355 <     * Creates a new phaser with the given numbers of registered
355 >     * Creates a new phaser with the given number of registered
356       * unarrived parties, initial phase number 0, and no parent.
357       *
358       * @param parties the number of parties required to trip barrier
# Line 381 | Line 384 | public class Phaser {
384      }
385  
386      /**
387 <     * Creates a new phaser with the given parent and numbers of
387 >     * Creates a new phaser with the given parent and number of
388       * registered unarrived parties. If parent is non-null, this phaser
389       * is registered with the parent and its initial phase number is
390       * the same as that of parent phaser.
# Line 407 | Line 410 | public class Phaser {
410  
411      /**
412       * Adds a new unarrived party to this phaser.
413 +     * If an ongoing invocation of {@link #onAdvance} is in progress,
414 +     * this method waits until its completion before registering.
415       *
416       * @return the arrival phase number to which this registration applied
417       * @throws IllegalStateException if attempting to register more
# Line 418 | Line 423 | public class Phaser {
423  
424      /**
425       * Adds the given number of new unarrived parties to this phaser.
426 +     * If an ongoing invocation of {@link #onAdvance} is in progress,
427 +     * this method waits until its completion before registering.
428       *
429 <     * @param parties the number of parties required to trip barrier
429 >     * @param parties the number of additional parties required to trip barrier
430       * @return the arrival phase number to which this registration applied
431       * @throws IllegalStateException if attempting to register more
432       * than the maximum supported number of parties
433 +     * @throws IllegalArgumentException if {@code parties < 0}
434       */
435      public int bulkRegister(int parties) {
436          if (parties < 0)
# Line 436 | Line 444 | public class Phaser {
444       * Shared code for register, bulkRegister
445       */
446      private int doRegister(int registrations) {
447 +        Phaser par = parent;
448 +        long s;
449          int phase;
450 <        for (;;) {
451 <            long s = getReconciledState();
452 <            phase = phaseOf(s);
453 <            int unarrived = unarrivedOf(s) + registrations;
454 <            int parties = partiesOf(s) + registrations;
455 <            if (phase < 0)
456 <                break;
457 <            if (parties > ushortMask || unarrived > ushortMask)
458 <                throw new IllegalStateException(badBounds(parties, unarrived));
459 <            if (phase == phaseOf(root.state) &&
460 <                casState(s, stateFor(phase, parties, unarrived)))
461 <                break;
450 >        while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
451 >            int p = partiesOf(s);
452 >            int u = unarrivedOf(s);
453 >            int unarrived = u + registrations;
454 >            int parties = p + registrations;
455 >            if (par == null || phase == phaseOf(root.state)) {
456 >                if (parties > ushortMask || unarrived > ushortMask)
457 >                    throw new IllegalStateException(badBounds(parties,
458 >                                                              unarrived));
459 >                else if (p != 0 && u == 0)       // back off if advancing
460 >                    Thread.yield();              // not worth actually blocking
461 >                else if (casState(s, stateFor(phase, parties, unarrived)))
462 >                    break;
463 >            }
464          }
465          return phase;
466      }
# Line 464 | Line 476 | public class Phaser {
476       * of unarrived parties would become negative
477       */
478      public int arrive() {
479 +        Phaser par = parent;
480 +        long s;
481          int phase;
482 <        for (;;) {
469 <            long s = state;
470 <            phase = phaseOf(s);
471 <            if (phase < 0)
472 <                break;
482 >        while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
483              int parties = partiesOf(s);
484              int unarrived = unarrivedOf(s) - 1;
485 <            if (unarrived > 0) {        // Not the last arrival
486 <                if (casState(s, s - 1)) // s-1 adds one arrival
485 >            if (parties == 0 || unarrived < 0)
486 >                throw new IllegalStateException(badBounds(parties,
487 >                                                          unarrived));
488 >            else if (unarrived > 0) {           // Not the last arrival
489 >                if (casState(s, s - 1))         // s-1 adds one arrival
490                      break;
491              }
492 <            else if (unarrived == 0) {  // the last arrival
493 <                Phaser par = parent;
494 <                if (par == null) {      // directly trip
495 <                    if (casState
496 <                        (s,
497 <                         trippedStateFor(onAdvance(phase, parties) ? -1 :
485 <                                         ((phase + 1) & phaseMask), parties))) {
486 <                        releaseWaiters(phase);
487 <                        break;
488 <                    }
489 <                }
490 <                else {                  // cascade to parent
491 <                    if (casState(s, s - 1)) { // zeroes unarrived
492 <                        par.arrive();
493 <                        reconcileState();
494 <                        break;
495 <                    }
492 >            else if (par == null) {             // directly trip
493 >                if (casState(s, trippedStateFor(onAdvance(phase, parties) ? -1 :
494 >                                                ((phase + 1) & phaseMask),
495 >                                                parties))) {
496 >                    releaseWaiters(phase);
497 >                    break;
498                  }
499              }
500 <            else if (phase != phaseOf(root.state)) // or if unreconciled
500 >            else if (phaseOf(root.state) == phase && casState(s, s - 1)) {
501 >                par.arrive();                   // cascade to parent
502                  reconcileState();
503 <            else
504 <                throw new IllegalStateException(badBounds(parties, unarrived));
503 >                break;
504 >            }
505          }
506          return phase;
507      }
# Line 517 | Line 520 | public class Phaser {
520       * of registered or unarrived parties would become negative
521       */
522      public int arriveAndDeregister() {
523 <        // similar code to arrive, but too different to merge
523 >        // similar to arrive, but too different to merge
524          Phaser par = parent;
525 +        long s;
526          int phase;
527 <        for (;;) {
524 <            long s = state;
525 <            phase = phaseOf(s);
526 <            if (phase < 0)
527 <                break;
527 >        while ((phase = phaseOf(s = par==null? state:reconcileState())) >= 0) {
528              int parties = partiesOf(s) - 1;
529              int unarrived = unarrivedOf(s) - 1;
530 <            if (parties >= 0) {
531 <                if (unarrived > 0 || (unarrived == 0 && par != null)) {
532 <                    if (casState
533 <                        (s,
534 <                         stateFor(phase, parties, unarrived))) {
535 <                        if (unarrived == 0) {
536 <                            par.arriveAndDeregister();
537 <                            reconcileState();
538 <                        }
539 <                        break;
540 <                    }
541 <                    continue;
542 <                }
543 <                if (unarrived == 0) {
544 <                    if (casState
545 <                        (s,
546 <                         trippedStateFor(onAdvance(phase, parties) ? -1 :
547 <                                         ((phase + 1) & phaseMask), parties))) {
548 <                        releaseWaiters(phase);
549 <                        break;
550 <                    }
551 <                    continue;
552 <                }
553 <                if (par != null && phase != phaseOf(root.state)) {
554 <                    reconcileState();
555 <                    continue;
530 >            if (parties < 0 || unarrived < 0)
531 >                throw new IllegalStateException(badBounds(parties,
532 >                                                          unarrived));
533 >            else if (unarrived > 0) {
534 >                if (casState(s, stateFor(phase, parties, unarrived)))
535 >                    break;
536 >            }
537 >            else if (par == null) {
538 >                if (casState(s, trippedStateFor(onAdvance(phase, parties)? -1:
539 >                                                (phase + 1) & phaseMask,
540 >                                                parties))) {
541 >                    releaseWaiters(phase);
542 >                    break;
543                  }
544              }
545 <            throw new IllegalStateException(badBounds(parties, unarrived));
545 >            else if (phaseOf(root.state) == phase &&
546 >                     casState(s, stateFor(phase, parties, 0))) {
547 >                if (parties == 0)
548 >                    par.arriveAndDeregister();
549 >                else
550 >                    par.arrive();
551 >                reconcileState();
552 >                break;
553 >            }
554          }
555          return phase;
556      }
# Line 564 | Line 559 | public class Phaser {
559       * Arrives at the barrier and awaits others. Equivalent in effect
560       * to {@code awaitAdvance(arrive())}.  If you need to await with
561       * interruption or timeout, you can arrange this with an analogous
562 <     * construction using one of the other forms of the awaitAdvance
563 <     * method.  If instead you need to deregister upon arrival use
564 <     * {@code arriveAndDeregister}. It is an unenforced usage error
565 <     * for an unregistered party to invoke this method.
562 >     * construction using one of the other forms of the {@code
563 >     * awaitAdvance} method.  If instead you need to deregister upon
564 >     * arrival, use {@link #arriveAndDeregister}. It is an unenforced
565 >     * usage error for an unregistered party to invoke this method.
566       *
567       * @return the arrival phase number, or a negative number if terminated
568       * @throws IllegalStateException if not terminated and the number
# Line 593 | Line 588 | public class Phaser {
588      public int awaitAdvance(int phase) {
589          if (phase < 0)
590              return phase;
591 <        long s = getReconciledState();
597 <        int p = phaseOf(s);
591 >        int p = getPhase();
592          if (p != phase)
593              return p;
600        if (unarrivedOf(s) == 0 && parent != null)
601            parent.awaitAdvance(phase);
602        // Fall here even if parent waited, to reconcile and help release
594          return untimedWait(phase);
595      }
596  
# Line 622 | Line 613 | public class Phaser {
613          throws InterruptedException {
614          if (phase < 0)
615              return phase;
616 <        long s = getReconciledState();
626 <        int p = phaseOf(s);
616 >        int p = getPhase();
617          if (p != phase)
618              return p;
629        if (unarrivedOf(s) == 0 && parent != null)
630            parent.awaitAdvanceInterruptibly(phase);
619          return interruptibleWait(phase);
620      }
621  
# Line 655 | Line 643 | public class Phaser {
643      public int awaitAdvanceInterruptibly(int phase,
644                                           long timeout, TimeUnit unit)
645          throws InterruptedException, TimeoutException {
646 +        long nanos = unit.toNanos(timeout);
647          if (phase < 0)
648              return phase;
649 <        long s = getReconciledState();
661 <        int p = phaseOf(s);
649 >        int p = getPhase();
650          if (p != phase)
651              return p;
652 <        if (unarrivedOf(s) == 0 && parent != null)
665 <            parent.awaitAdvanceInterruptibly(phase, timeout, unit);
666 <        return timedWait(phase, unit.toNanos(timeout));
652 >        return timedWait(phase, nanos);
653      }
654  
655      /**
# Line 674 | Line 660 | public class Phaser {
660       * unexpected exceptions.
661       */
662      public void forceTermination() {
663 <        for (;;) {
664 <            long s = getReconciledState();
665 <            int phase = phaseOf(s);
666 <            int parties = partiesOf(s);
667 <            int unarrived = unarrivedOf(s);
668 <            if (phase < 0 ||
669 <                casState(s, stateFor(-1, parties, unarrived))) {
684 <                releaseWaiters(0);
685 <                releaseWaiters(1);
686 <                if (parent != null)
687 <                    parent.forceTermination();
688 <                return;
689 <            }
690 <        }
663 >        Phaser r = root;    // force at root then reconcile
664 >        long s;
665 >        while (phaseOf(s = r.state) >= 0)
666 >            r.casState(s, stateFor(-1, partiesOf(s), unarrivedOf(s)));
667 >        reconcileState();
668 >        releaseWaiters(0);  // ensure wakeups on both queues
669 >        releaseWaiters(1);
670      }
671  
672      /**
# Line 707 | Line 686 | public class Phaser {
686       * @return the number of parties
687       */
688      public int getRegisteredParties() {
689 <        return partiesOf(state);
689 >        return partiesOf(getReconciledState());
690      }
691  
692      /**
# Line 717 | Line 696 | public class Phaser {
696       * @return the number of arrived parties
697       */
698      public int getArrivedParties() {
699 <        return arrivedOf(state);
699 >        return arrivedOf(getReconciledState());
700      }
701  
702      /**
# Line 727 | Line 706 | public class Phaser {
706       * @return the number of unarrived parties
707       */
708      public int getUnarrivedParties() {
709 <        return unarrivedOf(state);
709 >        return unarrivedOf(getReconciledState());
710      }
711  
712      /**
# Line 781 | Line 760 | public class Phaser {
760       * termination for other reasons should also preserve this
761       * property.
762       *
784     * <p>You may override this method to perform an action with side
785     * effects visible to participating tasks, but doing so requires
786     * care: Method {@code onAdvance} may be invoked more than once
787     * per transition.  Further, unless all parties register before
788     * any arrive, and all {@link #awaitAdvance} at each phase, then
789     * you cannot ensure lack of interference from other parties
790     * during the invocation of this method.
791     *
763       * @param phase the phase number on entering the barrier
764       * @param registeredParties the current number of registered parties
765       * @return {@code true} if this barrier should terminate
# Line 829 | Line 800 | public class Phaser {
800          volatile boolean wasInterrupted = false;
801          volatile Thread thread; // nulled to cancel wait
802          QNode next;
803 +
804          QNode(Phaser phaser, int phase, boolean interruptible,
805                boolean timed, long startTime, long nanos) {
806              this.phaser = phaser;
# Line 839 | Line 811 | public class Phaser {
811              this.nanos = nanos;
812              thread = Thread.currentThread();
813          }
814 +
815          public boolean isReleasable() {
816              return (thread == null ||
817                      phaser.getPhase() != phase ||
818                      (interruptible && wasInterrupted) ||
819                      (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
820          }
821 +
822          public boolean block() {
823              if (Thread.interrupted()) {
824                  wasInterrupted = true;
# Line 861 | Line 835 | public class Phaser {
835              }
836              return isReleasable();
837          }
838 +
839          void signal() {
840              Thread t = thread;
841              if (t != null) {
# Line 868 | Line 843 | public class Phaser {
843                  LockSupport.unpark(t);
844              }
845          }
846 +
847          boolean doWait() {
848              if (thread != null) {
849                  try {
850 <                    ForkJoinPool.managedBlock(this, false);
850 >                    ForkJoinPool.managedBlock(this);
851                  } catch (InterruptedException ie) {
852 +                    wasInterrupted = true; // can't currently happen
853                  }
854              }
855              return wasInterrupted;
856          }
880
857      }
858  
859      /**
# Line 919 | Line 895 | public class Phaser {
895                  node = new QNode(this, phase, false, false, 0, 0);
896              else if (!queued)
897                  queued = tryEnqueue(node);
898 <            else
899 <                interrupted = node.doWait();
898 >            else if (node.doWait())
899 >                interrupted = true;
900          }
901          if (node != null)
902              node.thread = null;
# Line 946 | Line 922 | public class Phaser {
922                  node = new QNode(this, phase, true, false, 0, 0);
923              else if (!queued)
924                  queued = tryEnqueue(node);
925 <            else
926 <                interrupted = node.doWait();
925 >            else if (node.doWait())
926 >                interrupted = true;
927          }
928          if (node != null)
929              node.thread = null;
# Line 978 | Line 954 | public class Phaser {
954                  node = new QNode(this, phase, true, true, startTime, nanos);
955              else if (!queued)
956                  queued = tryEnqueue(node);
957 <            else
958 <                interrupted = node.doWait();
957 >            else if (node.doWait())
958 >                interrupted = true;
959          }
960          if (node != null)
961              node.thread = null;

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines