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.59 by dl, Sat Nov 27 16:46:53 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 78 | Line 79 | import java.util.concurrent.locks.LockSu
79   * immediately return without updating phaser state or waiting for
80   * advance, and indicating (via a negative phase value) that execution
81   * is complete.  Termination is triggered when an invocation of {@code
82 < * onAdvance} returns {@code true}.  As illustrated below, when
82 > * onAdvance} returns {@code true}. The default implementation returns
83 > * {@code true} if a deregistration has caused the number of
84 > * registered parties to become zero.  As illustrated below, when
85   * phasers control actions with a fixed number of iterations, it is
86   * often convenient to override this method to cause termination when
87   * the current phase number reaches a threshold. Method {@link
88   * #forceTermination} is also available to abruptly release waiting
89   * threads and allow them to terminate.
90   *
91 < * <p> <b>Tiering.</b> Phasers may be <em>tiered</em> (i.e., arranged
92 < * in tree structures) to reduce contention. Phasers with large
93 < * numbers of parties that would otherwise experience heavy
91 > * <p> <b>Tiering.</b> Phasers may be <em>tiered</em> (i.e.,
92 > * constructed in tree structures) to reduce contention. Phasers with
93 > * large numbers of parties that would otherwise experience heavy
94   * synchronization contention costs may instead be set up so that
95   * groups of sub-phasers share a common parent.  This may greatly
96   * increase throughput even though it incurs greater per-operation
# Line 226 | Line 229 | public class Phaser {
229       * Barrier state representation. Conceptually, a barrier contains
230       * four values:
231       *
232 <     * * parties -- the number of parties to wait (16 bits)
233 <     * * unarrived -- the number of parties yet to hit barrier (16 bits)
234 <     * * phase -- the generation of the barrier (31 bits)
235 <     * * terminated -- set if barrier is terminated (1 bit)
232 >     * * unarrived -- the number of parties yet to hit barrier (bits  0-15)
233 >     * * parties -- the number of parties to wait              (bits 16-31)
234 >     * * phase -- the generation of the barrier                (bits 32-62)
235 >     * * terminated -- set if barrier is terminated            (bit  63 / sign)
236       *
237       * However, to efficiently maintain atomicity, these values are
238       * packed into a single (atomic) long. Termination uses the sign
239       * bit of 32 bit representation of phase, so phase is set to -1 on
240       * termination. Good performance relies on keeping state decoding
241       * 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.
242       */
243      private volatile long state;
244  
245 <    private static final int ushortMask = 0xffff;
246 <    private static final int phaseMask  = 0x7fffffff;
245 >    private static final int  MAX_PARTIES     = 0xffff;
246 >    private static final int  MAX_PHASE       = 0x7fffffff;
247 >    private static final int  PARTIES_SHIFT   = 16;
248 >    private static final int  PHASE_SHIFT     = 32;
249 >    private static final int  UNARRIVED_MASK  = 0xffff;      // to mask ints
250 >    private static final long PARTIES_MASK    = 0xffff0000L; // to mask longs
251 >    private static final long ONE_ARRIVAL     = 1L;
252 >    private static final long ONE_PARTY       = 1L << PARTIES_SHIFT;
253 >    private static final long TERMINATION_BIT = 1L << 63;
254 >
255 >    // The following unpacking methods are usually manually inlined
256  
257      private static int unarrivedOf(long s) {
258 <        return (int) (s & ushortMask);
258 >        return (int)s & UNARRIVED_MASK;
259      }
260  
261      private static int partiesOf(long s) {
262 <        return ((int) s) >>> 16;
262 >        return (int)s >>> PARTIES_SHIFT;
263      }
264  
265      private static int phaseOf(long s) {
266 <        return (int) (s >>> 32);
266 >        return (int) (s >>> PHASE_SHIFT);
267      }
268  
269      private static int arrivedOf(long s) {
270          return partiesOf(s) - unarrivedOf(s);
271      }
272  
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
273      /**
274       * The parent of this phaser, or null if none
275       */
# Line 290 | Line 281 | public class Phaser {
281       */
282      private final Phaser root;
283  
293    // Wait queues
294
284      /**
285       * Heads of Treiber stacks for waiting threads. To eliminate
286       * contention when releasing some threads while adding others, we
# Line 306 | Line 295 | public class Phaser {
295      }
296  
297      /**
298 <     * Returns current state, first resolving lagged propagation from
299 <     * root if necessary.
298 >     * Returns message string for bounds exceptions on arrival.
299 >     */
300 >    private String badArrive(long s) {
301 >        return "Attempted arrival of unregistered party for " +
302 >            stateToString(s);
303 >    }
304 >
305 >    /**
306 >     * Returns message string for bounds exceptions on registration.
307 >     */
308 >    private String badRegister(long s) {
309 >        return "Attempt to register more than " +
310 >            MAX_PARTIES + " parties for " + stateToString(s);
311 >    }
312 >
313 >    /**
314 >     * Main implementation for methods arrive and arriveAndDeregister.
315 >     * Manually tuned to speed up and minimize race windows for the
316 >     * common case of just decrementing unarrived field.
317 >     *
318 >     * @param adj - adjustment to apply to state -- either
319 >     * ONE_ARRIVAL (for arrive) or
320 >     * ONE_ARRIVAL|ONE_PARTY (for arriveAndDeregister)
321 >     */
322 >    private int doArrive(long adj) {
323 >        for (;;) {
324 >            long s = state;
325 >            int unarrived = (int)s & UNARRIVED_MASK;
326 >            int phase = (int)(s >>> PHASE_SHIFT);
327 >            if (phase < 0)
328 >                return phase;
329 >            else if (unarrived == 0) {
330 >                if (reconcileState() == s)     // recheck
331 >                    throw new IllegalStateException(badArrive(s));
332 >            }
333 >            else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) {
334 >                if (unarrived == 1) {
335 >                    long p = s & PARTIES_MASK; // unshifted parties field
336 >                    long lu = p >>> PARTIES_SHIFT;
337 >                    int u = (int)lu;
338 >                    int nextPhase = (phase + 1) & MAX_PHASE;
339 >                    long next = ((long)nextPhase << PHASE_SHIFT) | p | lu;
340 >                    final Phaser parent = this.parent;
341 >                    if (parent == null) {
342 >                        if (onAdvance(phase, u))
343 >                            next |= TERMINATION_BIT;
344 >                        UNSAFE.compareAndSwapLong(this, stateOffset, s, next);
345 >                        releaseWaiters(phase);
346 >                    }
347 >                    else {
348 >                        parent.doArrive((u == 0) ?
349 >                                        ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL);
350 >                        if ((int)(parent.state >>> PHASE_SHIFT) != nextPhase ||
351 >                            ((int)(state >>> PHASE_SHIFT) != nextPhase &&
352 >                             !UNSAFE.compareAndSwapLong(this, stateOffset,
353 >                                                        s, next)))
354 >                            reconcileState();
355 >                    }
356 >                }
357 >                return phase;
358 >            }
359 >        }
360 >    }
361 >
362 >    /**
363 >     * Implementation of register, bulkRegister
364 >     *
365 >     * @param registrations number to add to both parties and
366 >     * unarrived fields. Must be greater than zero.
367       */
368 <    private long getReconciledState() {
369 <        return (parent == null) ? state : reconcileState();
368 >    private int doRegister(int registrations) {
369 >        // adjustment to state
370 >        long adj = ((long)registrations << PARTIES_SHIFT) | registrations;
371 >        final Phaser parent = this.parent;
372 >        for (;;) {
373 >            long s = (parent == null) ? state : reconcileState();
374 >            int parties = (int)s >>> PARTIES_SHIFT;
375 >            int phase = (int)(s >>> PHASE_SHIFT);
376 >            if (phase < 0)
377 >                return phase;
378 >            else if (registrations > MAX_PARTIES - parties)
379 >                throw new IllegalStateException(badRegister(s));
380 >            else if ((parties == 0 && parent == null) || // first reg of root
381 >                     ((int)s & UNARRIVED_MASK) != 0) {   // not advancing
382 >                if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s + adj))
383 >                    return phase;
384 >            }
385 >            else if (parties != 0)               // wait for onAdvance
386 >                internalAwaitAdvance(phase, null);
387 >            else {                               // 1st registration of child
388 >                synchronized(this) {             // register parent first
389 >                    if (reconcileState() == s) { // recheck under lock
390 >                        parent.doRegister(1);    // OK if throws IllegalState
391 >                        for (;;) {               // simpler form of outer loop
392 >                            s = reconcileState();
393 >                            phase = (int)(s >>> PHASE_SHIFT);
394 >                            if (phase < 0 ||
395 >                                UNSAFE.compareAndSwapLong(this, stateOffset,
396 >                                                          s, s + adj))
397 >                                return phase;
398 >                        }
399 >                    }
400 >                }
401 >            }
402 >        }
403      }
404  
405      /**
406 <     * Recursively resolves state.
406 >     * Recursively resolves lagged phase propagation from root if necessary.
407       */
408      private long reconcileState() {
409          Phaser par = parent;
410          long s = state;
411          if (par != null) {
412 <            int phase, rootPhase;
413 <            while ((phase = phaseOf(s)) >= 0 &&
414 <                   (rootPhase = phaseOf(root.state)) != phase &&
415 <                   (rootPhase < 0 || unarrivedOf(s) == 0)) {
416 <                int parentPhase = phaseOf(par.getReconciledState());
417 <                if (parentPhase != phase) {
418 <                    long next = trippedStateFor(parentPhase, partiesOf(s));
419 <                    if (state == s)
420 <                        UNSAFE.compareAndSwapLong(this, stateOffset, s, next);
412 >            Phaser rt = root;
413 >            int phase, rPhase;
414 >            while ((phase = (int)(s >>> PHASE_SHIFT)) >= 0 &&
415 >                   (rPhase = (int)(rt.state >>> PHASE_SHIFT)) != phase) {
416 >                if ((int)(par.state >>> PHASE_SHIFT) != rPhase)
417 >                    par.reconcileState();
418 >                else if (rPhase < 0 || ((int)s & UNARRIVED_MASK) == 0) {
419 >                    long u = s & PARTIES_MASK; // reset unarrived to parties
420 >                    long next = ((((long) rPhase) << PHASE_SHIFT) | u |
421 >                                 (u >>> PARTIES_SHIFT));
422 >                    UNSAFE.compareAndSwapLong(this, stateOffset, s, next);
423                  }
424                  s = state;
425              }
# Line 358 | Line 449 | public class Phaser {
449      }
450  
451      /**
452 <     * Creates a new phaser with the given parent, without any
453 <     * initially registered parties. If parent is non-null this phaser
454 <     * is registered with the parent and its initial phase number is
455 <     * the same as that of parent phaser.
452 >     * Creates a new phaser with the given parent, and without any
453 >     * initially registered parties.  Any thread using this phaser
454 >     * will need to first register for it, at which point, if the
455 >     * given parent is non-null, this phaser will also be registered
456 >     * with the parent.
457 >     *
458 >     * Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}.
459       *
460       * @param parent the parent phaser
461       */
# Line 371 | Line 465 | public class Phaser {
465  
466      /**
467       * Creates a new phaser with the given parent and number of
468 <     * registered unarrived parties. If parent is non-null, this phaser
469 <     * is registered with the parent and its initial phase number is
470 <     * the same as that of parent phaser.
468 >     * registered unarrived parties. If parent is non-null and
469 >     * the number of parties is non-zero, this phaser is registered
470 >     * with the parent.
471       *
472       * @param parent the parent phaser
473       * @param parties the number of parties required to trip barrier
# Line 381 | Line 475 | public class Phaser {
475       * or greater than the maximum number of parties supported
476       */
477      public Phaser(Phaser parent, int parties) {
478 <        if (parties < 0 || parties > ushortMask)
478 >        if (parties >>> PARTIES_SHIFT != 0)
479              throw new IllegalArgumentException("Illegal number of parties");
480          int phase;
481          this.parent = parent;
# Line 390 | Line 484 | public class Phaser {
484              this.root = r;
485              this.evenQ = r.evenQ;
486              this.oddQ = r.oddQ;
487 <            phase = parent.register();
487 >            phase = (parties == 0) ? parent.getPhase() : parent.doRegister(1);
488          }
489          else {
490              this.root = this;
# Line 398 | Line 492 | public class Phaser {
492              this.oddQ = new AtomicReference<QNode>();
493              phase = 0;
494          }
495 <        this.state = trippedStateFor(phase, parties);
495 >        long p = (long)parties;
496 >        this.state = (((long)phase) << PHASE_SHIFT) | p | (p << PARTIES_SHIFT);
497      }
498  
499      /**
500 <     * Adds a new unarrived party to this phaser.
501 <     * If an ongoing invocation of {@link #onAdvance} is in progress,
502 <     * this method may wait until its completion before registering.
500 >     * Adds a new unarrived party to this phaser.  If an ongoing
501 >     * invocation of {@link #onAdvance} is in progress, this method
502 >     * may wait until its completion before registering.  If this
503 >     * phaser has a parent, and this phaser previously had no
504 >     * registered parties, this phaser is also registered with its
505 >     * parent.
506       *
507       * @return the arrival phase number to which this registration applied
508       * @throws IllegalStateException if attempting to register more
# Line 418 | Line 516 | public class Phaser {
516       * Adds the given number of new unarrived parties to this phaser.
517       * If an ongoing invocation of {@link #onAdvance} is in progress,
518       * this method may wait until its completion before registering.
519 +     * If this phaser has a parent, and the given number of parities
520 +     * is greater than zero, and this phaser previously had no
521 +     * registered parties, this phaser is also registered with its
522 +     * parent.
523       *
524       * @param parties the number of additional parties required to trip barrier
525       * @return the arrival phase number to which this registration applied
# Line 428 | Line 530 | public class Phaser {
530      public int bulkRegister(int parties) {
531          if (parties < 0)
532              throw new IllegalArgumentException();
533 <        if (parties == 0)
533 >        else if (parties == 0)
534              return getPhase();
535          return doRegister(parties);
536      }
537  
538      /**
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    /**
539       * Arrives at the barrier, but does not wait for others.  (You can
540 <     * in turn wait for others via {@link #awaitAdvance}).  It is an
541 <     * unenforced usage error for an unregistered party to invoke this
542 <     * method.
540 >     * in turn wait for others via {@link #awaitAdvance}).  It is a
541 >     * usage error for an unregistered party to invoke this
542 >     * method. However, it is possible that this error will result in
543 >     * an {code IllegalStateException} only when some <em>other</em>
544 >     * party arrives.
545       *
546       * @return the arrival phase number, or a negative value if terminated
547       * @throws IllegalStateException if not terminated and the number
548       * of unarrived parties would become negative
549       */
550      public int arrive() {
551 <        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;
551 >        return doArrive(ONE_ARRIVAL);
552      }
553  
554      /**
# Line 506 | Line 557 | public class Phaser {
557       * required to trip the barrier in future phases.  If this phaser
558       * has a parent, and deregistration causes this phaser to have
559       * zero parties, this phaser also arrives at and is deregistered
560 <     * from its parent.  It is an unenforced usage error for an
561 <     * unregistered party to invoke this method.
560 >     * from its parent.  It is a usage error for an unregistered party
561 >     * to invoke this method. However, it is possible that this error
562 >     * will result in an {code IllegalStateException} only when some
563 >     * <em>other</em> party arrives.
564       *
565       * @return the arrival phase number, or a negative value if terminated
566       * @throws IllegalStateException if not terminated and the number
567       * of registered or unarrived parties would become negative
568       */
569      public int arriveAndDeregister() {
570 <        // 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;
570 >        return doArrive(ONE_ARRIVAL|ONE_PARTY);
571      }
572  
573      /**
# Line 558 | Line 576 | public class Phaser {
576       * interruption or timeout, you can arrange this with an analogous
577       * construction using one of the other forms of the {@code
578       * awaitAdvance} method.  If instead you need to deregister upon
579 <     * arrival, use {@link #arriveAndDeregister}. It is an unenforced
580 <     * usage error for an unregistered party to invoke this method.
579 >     * arrival, use {@link #arriveAndDeregister}.  It is a usage error
580 >     * for an unregistered party to invoke this method. However, it is
581 >     * possible that this error will result in an {code
582 >     * IllegalStateException} only when some <em>other</em> party
583 >     * arrives.
584       *
585       * @return the arrival phase number, or a negative number if terminated
586       * @throws IllegalStateException if not terminated and the number
# Line 584 | Line 605 | public class Phaser {
605      public int awaitAdvance(int phase) {
606          if (phase < 0)
607              return phase;
608 <        int p = getPhase();
609 <        if (p != phase)
610 <            return p;
590 <        return untimedWait(phase);
608 >        long s = (parent == null) ? state : reconcileState();
609 >        int p = (int)(s >>> PHASE_SHIFT);
610 >        return (p != phase) ? p : internalAwaitAdvance(phase, null);
611      }
612  
613      /**
# Line 608 | Line 628 | public class Phaser {
628          throws InterruptedException {
629          if (phase < 0)
630              return phase;
631 <        int p = getPhase();
632 <        if (p != phase)
633 <            return p;
634 <        return interruptibleWait(phase);
631 >        long s = (parent == null) ? state : reconcileState();
632 >        int p = (int)(s >>> PHASE_SHIFT);
633 >        if (p == phase) {
634 >            QNode node = new QNode(this, phase, true, false, 0L);
635 >            p = internalAwaitAdvance(phase, node);
636 >            if (node.wasInterrupted)
637 >                throw new InterruptedException();
638 >        }
639 >        return p;
640      }
641  
642      /**
# Line 637 | Line 662 | public class Phaser {
662      public int awaitAdvanceInterruptibly(int phase,
663                                           long timeout, TimeUnit unit)
664          throws InterruptedException, TimeoutException {
640        long nanos = unit.toNanos(timeout);
665          if (phase < 0)
666              return phase;
667 <        int p = getPhase();
668 <        if (p != phase)
669 <            return p;
670 <        return timedWait(phase, nanos);
667 >        long s = (parent == null) ? state : reconcileState();
668 >        int p = (int)(s >>> PHASE_SHIFT);
669 >        if (p == phase) {
670 >            long nanos = unit.toNanos(timeout);
671 >            QNode node = new QNode(this, phase, true, true, nanos);
672 >            p = internalAwaitAdvance(phase, node);
673 >            if (node.wasInterrupted)
674 >                throw new InterruptedException();
675 >            else if (p == phase)
676 >                throw new TimeoutException();
677 >        }
678 >        return p;
679      }
680  
681      /**
682 <     * Forces this barrier to enter termination state. Counts of
683 <     * arrived and registered parties are unaffected. If this phaser
684 <     * has a parent, it too is terminated. This method may be useful
685 <     * for coordinating recovery after one or more tasks encounter
686 <     * unexpected exceptions.
682 >     * Forces this barrier to enter termination state.  Counts of
683 >     * arrived and registered parties are unaffected.  If this phaser
684 >     * is a member of a tiered set of phasers, then all of the phasers
685 >     * in the set are terminated.  If this phaser is already
686 >     * terminated, this method has no effect.  This method may be
687 >     * useful for coordinating recovery after one or more tasks
688 >     * encounter unexpected exceptions.
689       */
690      public void forceTermination() {
691 <        Phaser r = root;    // force at root then reconcile
691 >        // Only need to change root state
692 >        final Phaser root = this.root;
693          long s;
694 <        while (phaseOf(s = r.state) >= 0)
695 <            UNSAFE.compareAndSwapLong(r, stateOffset, s,
696 <                                      stateFor(-1, partiesOf(s),
697 <                                               unarrivedOf(s)));
698 <        reconcileState();
699 <        releaseWaiters(0);  // ensure wakeups on both queues
700 <        releaseWaiters(1);
694 >        while ((s = root.state) >= 0) {
695 >            if (UNSAFE.compareAndSwapLong(root, stateOffset,
696 >                                          s, s | TERMINATION_BIT)) {
697 >                releaseWaiters(0); // signal all threads
698 >                releaseWaiters(1);
699 >                return;
700 >            }
701 >        }
702      }
703  
704      /**
# Line 673 | Line 709 | public class Phaser {
709       * @return the phase number, or a negative value if terminated
710       */
711      public final int getPhase() {
712 <        return phaseOf(getReconciledState());
712 >        return (int)(root.state >>> PHASE_SHIFT);
713      }
714  
715      /**
# Line 682 | Line 718 | public class Phaser {
718       * @return the number of parties
719       */
720      public int getRegisteredParties() {
721 <        return partiesOf(getReconciledState());
721 >        return partiesOf(state);
722      }
723  
724      /**
# Line 692 | Line 728 | public class Phaser {
728       * @return the number of arrived parties
729       */
730      public int getArrivedParties() {
731 <        return arrivedOf(getReconciledState());
731 >        return arrivedOf(parent==null? state : reconcileState());
732      }
733  
734      /**
# Line 702 | Line 738 | public class Phaser {
738       * @return the number of unarrived parties
739       */
740      public int getUnarrivedParties() {
741 <        return unarrivedOf(getReconciledState());
741 >        return unarrivedOf(parent==null? state : reconcileState());
742      }
743  
744      /**
# Line 730 | Line 766 | public class Phaser {
766       * @return {@code true} if this barrier has been terminated
767       */
768      public boolean isTerminated() {
769 <        return getPhase() < 0;
769 >        return root.state < 0L;
770      }
771  
772      /**
# Line 746 | Line 782 | public class Phaser {
782       * which case no advance occurs.
783       *
784       * <p>The arguments to this method provide the state of the phaser
785 <     * prevailing for the current transition.  The results and effects
786 <     * of invoking phase-related methods (including {@code getPhase}
751 <     * as well as arrival, registration, and waiting methods) from
785 >     * prevailing for the current transition.  The effects of invoking
786 >     * arrival, registration, and waiting methods on this Phaser from
787       * within {@code onAdvance} are unspecified and should not be
788 <     * relied on. Similarly, while it is possible to override this
789 <     * method to produce side-effects visible to participating tasks,
790 <     * it is in general safe to do so only in designs in which all
791 <     * parties register before any arrive, and all {@link
792 <     * #awaitAdvance} at each phase.
793 <     *
794 <     * <p>The default version returns {@code true} when the number of
795 <     * registered parties is zero. Normally, overrides that arrange
796 <     * termination for other reasons should also preserve this
797 <     * property.
788 >     * relied on.
789 >     *
790 >     * <p>If this Phaser is a member of a tiered set of Phasers, then
791 >     * {@code onAdvance} is invoked only for its root Phaser on each
792 >     * advance.
793 >     *
794 >     * <p>To support the most common use cases, the default
795 >     * implementation of this method returns {@code true} when the
796 >     * number of registered parties has become zero as the result of a
797 >     * party invoking {@code arriveAndDeregister}.  You can disable
798 >     * this behavior, thus enabling continuation upon future
799 >     * registrations, by overriding this method to always return
800 >     * {@code false}:
801 >     *
802 >     * <pre> {@code
803 >     * Phaser phaser = new Phaser() {
804 >     *   protected boolean onAdvance(int phase, int parties) { return false; }
805 >     * }}</pre>
806       *
807       * @param phase the phase number on entering the barrier
808       * @param registeredParties the current number of registered parties
# Line 779 | Line 822 | public class Phaser {
822       * @return a string identifying this barrier, as well as its state
823       */
824      public String toString() {
825 <        long s = getReconciledState();
825 >        return stateToString(reconcileState());
826 >    }
827 >
828 >    /**
829 >     * Implementation of toString and string-based error messages
830 >     */
831 >    private String stateToString(long s) {
832          return super.toString() +
833              "[phase = " + phaseOf(s) +
834              " parties = " + partiesOf(s) +
835              " arrived = " + arrivedOf(s) + "]";
836      }
837  
838 <    // methods for waiting
838 >    // Waiting mechanics
839 >
840 >    /**
841 >     * Removes and signals threads from queue for phase.
842 >     */
843 >    private void releaseWaiters(int phase) {
844 >        AtomicReference<QNode> head = queueFor(phase);
845 >        QNode q;
846 >        int p;
847 >        while ((q = head.get()) != null &&
848 >               ((p = q.phase) == phase ||
849 >                (int)(root.state >>> PHASE_SHIFT) != p)) {
850 >            if (head.compareAndSet(q, q.next))
851 >                q.signal();
852 >        }
853 >    }
854 >
855 >    /** The number of CPUs, for spin control */
856 >    private static final int NCPU = Runtime.getRuntime().availableProcessors();
857 >
858 >    /**
859 >     * The number of times to spin before blocking while waiting for
860 >     * advance, per arrival while waiting. On multiprocessors, fully
861 >     * blocking and waking up a large number of threads all at once is
862 >     * usually a very slow process, so we use rechargeable spins to
863 >     * avoid it when threads regularly arrive: When a thread in
864 >     * internalAwaitAdvance notices another arrival before blocking,
865 >     * and there appear to be enough CPUs available, it spins
866 >     * SPINS_PER_ARRIVAL more times before blocking. Plus, even on
867 >     * uniprocessors, there is at least one intervening Thread.yield
868 >     * before blocking. The value trades off good-citizenship vs big
869 >     * unnecessary slowdowns.
870 >     */
871 >    static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
872 >
873 >    /**
874 >     * Possibly blocks and waits for phase to advance unless aborted.
875 >     *
876 >     * @param phase current phase
877 >     * @param node if non-null, the wait node to track interrupt and timeout;
878 >     * if null, denotes noninterruptible wait
879 >     * @return current phase
880 >     */
881 >    private int internalAwaitAdvance(int phase, QNode node) {
882 >        Phaser current = this;       // to eventually wait at root if tiered
883 >        boolean queued = false;      // true when node is enqueued
884 >        int lastUnarrived = -1;      // to increase spins upon change
885 >        int spins = SPINS_PER_ARRIVAL;
886 >        long s;
887 >        int p;
888 >        while ((p = (int)((s = current.state) >>> PHASE_SHIFT)) == phase) {
889 >            Phaser par;
890 >            int unarrived = (int)s & UNARRIVED_MASK;
891 >            if (unarrived != lastUnarrived) {
892 >                if (lastUnarrived == -1) // ensure old queue clean
893 >                    releaseWaiters(phase-1);
894 >                if ((lastUnarrived = unarrived) < NCPU)
895 >                    spins += SPINS_PER_ARRIVAL;
896 >            }
897 >            else if (unarrived == 0 && (par = current.parent) != null) {
898 >                current = par;       // if all arrived, use parent
899 >                par = par.parent;
900 >                lastUnarrived = -1;
901 >            }
902 >            else if (spins > 0) {
903 >                if (--spins == (SPINS_PER_ARRIVAL >>> 1))
904 >                    Thread.yield();  // yield midway through spin
905 >            }
906 >            else if (node == null)   // must be noninterruptible
907 >                node = new QNode(this, phase, false, false, 0L);
908 >            else if (node.isReleasable()) {
909 >                if ((p = (int)(root.state >>> PHASE_SHIFT)) != phase)
910 >                    break;
911 >                else
912 >                    return phase;    // aborted
913 >            }
914 >            else if (!queued) {      // push onto queue
915 >                AtomicReference<QNode> head = queueFor(phase);
916 >                QNode q = head.get();
917 >                if (q == null || q.phase == phase) {
918 >                    node.next = q;
919 >                    if ((p = (int)(root.state >>> PHASE_SHIFT)) != phase)
920 >                        break;       // recheck to avoid stale enqueue
921 >                    else
922 >                        queued = head.compareAndSet(q, node);
923 >                }
924 >            }
925 >            else {
926 >                try {
927 >                    ForkJoinPool.managedBlock(node);
928 >                } catch (InterruptedException ie) {
929 >                    node.wasInterrupted = true;
930 >                }
931 >            }
932 >        }
933 >        releaseWaiters(phase);
934 >        if (node != null)
935 >            node.onRelease();
936 >        return p;
937 >    }
938  
939      /**
940       * Wait nodes for Treiber stack representing wait queue
# Line 794 | Line 942 | public class Phaser {
942      static final class QNode implements ForkJoinPool.ManagedBlocker {
943          final Phaser phaser;
944          final int phase;
797        final long startTime;
798        final long nanos;
799        final boolean timed;
945          final boolean interruptible;
946 <        volatile boolean wasInterrupted = false;
946 >        final boolean timed;
947 >        boolean wasInterrupted;
948 >        long nanos;
949 >        long lastTime;
950          volatile Thread thread; // nulled to cancel wait
951          QNode next;
952  
953          QNode(Phaser phaser, int phase, boolean interruptible,
954 <              boolean timed, long startTime, long nanos) {
954 >              boolean timed, long nanos) {
955              this.phaser = phaser;
956              this.phase = phase;
809            this.timed = timed;
957              this.interruptible = interruptible;
811            this.startTime = startTime;
958              this.nanos = nanos;
959 +            this.timed = timed;
960 +            this.lastTime = timed? System.nanoTime() : 0L;
961              thread = Thread.currentThread();
962          }
963  
964          public boolean isReleasable() {
965 <            return (thread == null ||
966 <                    phaser.getPhase() != phase ||
967 <                    (interruptible && wasInterrupted) ||
968 <                    (timed && (nanos - (System.nanoTime() - startTime)) <= 0));
965 >            Thread t = thread;
966 >            if (t != null) {
967 >                if (phaser.getPhase() != phase)
968 >                    t = null;
969 >                else {
970 >                    if (Thread.interrupted())
971 >                        wasInterrupted = true;
972 >                    if (interruptible && wasInterrupted)
973 >                        t = null;
974 >                    else if (timed) {
975 >                        if (nanos > 0) {
976 >                            long now = System.nanoTime();
977 >                            nanos -= now - lastTime;
978 >                            lastTime = now;
979 >                        }
980 >                        if (nanos <= 0)
981 >                            t = null;
982 >                    }
983 >                }
984 >                if (t != null)
985 >                    return false;
986 >                thread = null;
987 >            }
988 >            return true;
989          }
990  
991          public boolean block() {
992 <            if (Thread.interrupted()) {
993 <                wasInterrupted = true;
994 <                if (interruptible)
827 <                    return true;
828 <            }
829 <            if (!timed)
992 >            if (isReleasable())
993 >                return true;
994 >            else if (!timed)
995                  LockSupport.park(this);
996 <            else {
997 <                long waitTime = nanos - (System.nanoTime() - startTime);
833 <                if (waitTime <= 0)
834 <                    return true;
835 <                LockSupport.parkNanos(this, waitTime);
836 <            }
996 >            else if (nanos > 0)
997 >                LockSupport.parkNanos(this, nanos);
998              return isReleasable();
999          }
1000  
# Line 845 | Line 1006 | public class Phaser {
1006              }
1007          }
1008  
1009 <        boolean doWait() {
1010 <            if (thread != null) {
1011 <                try {
1012 <                    ForkJoinPool.managedBlock(this);
1013 <                } 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.
862 <     */
863 <    private void releaseWaiters(int phase) {
864 <        AtomicReference<QNode> head = queueFor(phase);
865 <        QNode q;
866 <        while ((q = head.get()) != null) {
867 <            if (head.compareAndSet(q, q.next))
868 <                q.signal();
869 <        }
870 <    }
871 <
872 <    /**
873 <     * Tries to enqueue given node in the appropriate wait queue.
874 <     *
875 <     * @return true if successful
876 <     */
877 <    private boolean tryEnqueue(QNode node) {
878 <        AtomicReference<QNode> head = queueFor(node.phase);
879 <        return head.compareAndSet(node.next = head.get(), node);
880 <    }
881 <
882 <    /**
883 <     * The number of times to spin before blocking waiting for advance.
884 <     */
885 <    static final int MAX_SPINS =
886 <        Runtime.getRuntime().availableProcessors() == 1 ? 0 : 1 << 8;
887 <
888 <    /**
889 <     * Enqueues node and waits unless aborted or signalled.
890 <     *
891 <     * @return current phase
892 <     */
893 <    private int untimedWait(int phase) {
894 <        QNode node = null;
895 <        boolean queued = false;
896 <        boolean interrupted = false;
897 <        int spins = MAX_SPINS;
898 <        int p;
899 <        while ((p = getPhase()) == phase) {
900 <            if (Thread.interrupted())
901 <                interrupted = true;
902 <            else if (spins > 0) {
903 <                if (--spins == 0)
904 <                    Thread.yield();
905 <            }
906 <            else if (node == null)
907 <                node = new QNode(this, phase, false, false, 0, 0);
908 <            else if (!queued)
909 <                queued = tryEnqueue(node);
910 <            else if (node.doWait())
911 <                interrupted = true;
912 <        }
913 <        if (node != null)
914 <            node.thread = null;
915 <        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();
937 <            }
938 <            else if (node == null)
939 <                node = new QNode(this, phase, true, false, 0, 0);
940 <            else if (!queued)
941 <                queued = tryEnqueue(node);
942 <            else if (node.doWait())
943 <                interrupted = true;
1009 >        void onRelease() { // actions upon return from internalAwaitAdvance
1010 >            if (!interruptible && wasInterrupted)
1011 >                Thread.currentThread().interrupt();
1012 >            if (thread != null)
1013 >                thread = null;
1014          }
945        if (node != null)
946            node.thread = null;
947        if (p != phase || (p = getPhase()) != phase)
948            releaseWaiters(phase);
949        if (interrupted)
950            throw new InterruptedException();
951        return p;
952    }
1015  
954    /**
955     * Timeout version.
956     * @return current phase
957     */
958    private int timedWait(int phase, long nanos)
959        throws InterruptedException, TimeoutException {
960        long startTime = System.nanoTime();
961        QNode node = null;
962        boolean queued = false;
963        boolean interrupted = false;
964        int spins = MAX_SPINS;
965        int p;
966        while ((p = getPhase()) == phase && !interrupted) {
967            if (Thread.interrupted())
968                interrupted = true;
969            else if (nanos - (System.nanoTime() - startTime) <= 0)
970                break;
971            else if (spins > 0) {
972                if (--spins == 0)
973                    Thread.yield();
974            }
975            else if (node == null)
976                node = new QNode(this, phase, true, true, startTime, nanos);
977            else if (!queued)
978                queued = tryEnqueue(node);
979            else if (node.doWait())
980                interrupted = true;
981        }
982        if (node != null)
983            node.thread = null;
984        if (p != phase || (p = getPhase()) != phase)
985            releaseWaiters(phase);
986        if (interrupted)
987            throw new InterruptedException();
988        if (p == phase)
989            throw new TimeoutException();
990        return p;
1016      }
1017  
1018      // Unsafe mechanics

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines