1771N/A/*
1771N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
1771N/A *
1771N/A * This code is free software; you can redistribute it and/or modify it
1771N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
1771N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
1771N/A *
1771N/A * This code is distributed in the hope that it will be useful, but WITHOUT
1771N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
1771N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
1771N/A * version 2 for more details (a copy is included in the LICENSE file that
1771N/A * accompanied this code).
1771N/A *
1771N/A * You should have received a copy of the GNU General Public License version
1771N/A * 2 along with this work; if not, write to the Free Software Foundation,
1771N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
1771N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
1771N/A */
1771N/A
1771N/A/*
1771N/A * This file is available under and governed by the GNU General Public
1771N/A * License version 2 only, as published by the Free Software Foundation.
1771N/A * However, the following notice accompanied the original version of this
1771N/A * file:
1771N/A *
1771N/A * Written by Doug Lea with assistance from members of JCP JSR-166
1771N/A * Expert Group and released to the public domain, as explained at
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
1771N/A */
1771N/A
1771N/Apackage java.util.concurrent;
1771N/A
3387N/Aimport java.util.concurrent.TimeUnit;
3387N/Aimport java.util.concurrent.TimeoutException;
1771N/Aimport java.util.concurrent.atomic.AtomicReference;
1771N/Aimport java.util.concurrent.locks.LockSupport;
1771N/A
1771N/A/**
1771N/A * A reusable synchronization barrier, similar in functionality to
1771N/A * {@link java.util.concurrent.CyclicBarrier CyclicBarrier} and
1771N/A * {@link java.util.concurrent.CountDownLatch CountDownLatch}
1771N/A * but supporting more flexible usage.
1771N/A *
1771N/A * <p> <b>Registration.</b> Unlike the case for other barriers, the
1771N/A * number of parties <em>registered</em> to synchronize on a phaser
1771N/A * may vary over time. Tasks may be registered at any time (using
1771N/A * methods {@link #register}, {@link #bulkRegister}, or forms of
1771N/A * constructors establishing initial numbers of parties), and
1771N/A * optionally deregistered upon any arrival (using {@link
1771N/A * #arriveAndDeregister}). As is the case with most basic
1771N/A * synchronization constructs, registration and deregistration affect
1771N/A * only internal counts; they do not establish any further internal
1771N/A * bookkeeping, so tasks cannot query whether they are registered.
1771N/A * (However, you can introduce such bookkeeping by subclassing this
1771N/A * class.)
1771N/A *
1771N/A * <p> <b>Synchronization.</b> Like a {@code CyclicBarrier}, a {@code
1771N/A * Phaser} may be repeatedly awaited. Method {@link
1771N/A * #arriveAndAwaitAdvance} has effect analogous to {@link
1771N/A * java.util.concurrent.CyclicBarrier#await CyclicBarrier.await}. Each
3387N/A * generation of a phaser has an associated phase number. The phase
3387N/A * number starts at zero, and advances when all parties arrive at the
3387N/A * phaser, wrapping around to zero after reaching {@code
1771N/A * Integer.MAX_VALUE}. The use of phase numbers enables independent
3387N/A * control of actions upon arrival at a phaser and upon awaiting
1771N/A * others, via two kinds of methods that may be invoked by any
1771N/A * registered party:
1771N/A *
1771N/A * <ul>
1771N/A *
1771N/A * <li> <b>Arrival.</b> Methods {@link #arrive} and
3387N/A * {@link #arriveAndDeregister} record arrival. These methods
3387N/A * do not block, but return an associated <em>arrival phase
3387N/A * number</em>; that is, the phase number of the phaser to which
3387N/A * the arrival applied. When the final party for a given phase
3387N/A * arrives, an optional action is performed and the phase
3387N/A * advances. These actions are performed by the party
3387N/A * triggering a phase advance, and are arranged by overriding
3387N/A * method {@link #onAdvance(int, int)}, which also controls
3387N/A * termination. Overriding this method is similar to, but more
3387N/A * flexible than, providing a barrier action to a {@code
3387N/A * CyclicBarrier}.
1771N/A *
1771N/A * <li> <b>Waiting.</b> Method {@link #awaitAdvance} requires an
1771N/A * argument indicating an arrival phase number, and returns when
3387N/A * the phaser advances to (or is already at) a different phase.
1771N/A * Unlike similar constructions using {@code CyclicBarrier},
1771N/A * method {@code awaitAdvance} continues to wait even if the
1771N/A * waiting thread is interrupted. Interruptible and timeout
1771N/A * versions are also available, but exceptions encountered while
1771N/A * tasks wait interruptibly or with timeout do not change the
3387N/A * state of the phaser. If necessary, you can perform any
1771N/A * associated recovery within handlers of those exceptions,
1771N/A * often after invoking {@code forceTermination}. Phasers may
1771N/A * also be used by tasks executing in a {@link ForkJoinPool},
1771N/A * which will ensure sufficient parallelism to execute tasks
1771N/A * when others are blocked waiting for a phase to advance.
1771N/A *
1771N/A * </ul>
1771N/A *
3387N/A * <p> <b>Termination.</b> A phaser may enter a <em>termination</em>
3387N/A * state, that may be checked using method {@link #isTerminated}. Upon
3387N/A * termination, all synchronization methods immediately return without
3387N/A * waiting for advance, as indicated by a negative return value.
3387N/A * Similarly, attempts to register upon termination have no effect.
3387N/A * Termination is triggered when an invocation of {@code onAdvance}
3387N/A * returns {@code true}. The default implementation returns {@code
3387N/A * true} if a deregistration has caused the number of registered
3387N/A * parties to become zero. As illustrated below, when phasers control
3387N/A * actions with a fixed number of iterations, it is often convenient
3387N/A * to override this method to cause termination when the current phase
3387N/A * number reaches a threshold. Method {@link #forceTermination} is
3387N/A * also available to abruptly release waiting threads and allow them
3387N/A * to terminate.
1771N/A *
3387N/A * <p> <b>Tiering.</b> Phasers may be <em>tiered</em> (i.e.,
3387N/A * constructed in tree structures) to reduce contention. Phasers with
3387N/A * large numbers of parties that would otherwise experience heavy
1771N/A * synchronization contention costs may instead be set up so that
1771N/A * groups of sub-phasers share a common parent. This may greatly
1771N/A * increase throughput even though it incurs greater per-operation
1771N/A * overhead.
1771N/A *
3387N/A * <p>In a tree of tiered phasers, registration and deregistration of
3387N/A * child phasers with their parent are managed automatically.
3387N/A * Whenever the number of registered parties of a child phaser becomes
3387N/A * non-zero (as established in the {@link #Phaser(Phaser,int)}
3387N/A * constructor, {@link #register}, or {@link #bulkRegister}), the
3387N/A * child phaser is registered with its parent. Whenever the number of
3387N/A * registered parties becomes zero as the result of an invocation of
3387N/A * {@link #arriveAndDeregister}, the child phaser is deregistered
3387N/A * from its parent.
3387N/A *
1771N/A * <p><b>Monitoring.</b> While synchronization methods may be invoked
1771N/A * only by registered parties, the current state of a phaser may be
1771N/A * monitored by any caller. At any given moment there are {@link
1771N/A * #getRegisteredParties} parties in total, of which {@link
1771N/A * #getArrivedParties} have arrived at the current phase ({@link
1771N/A * #getPhase}). When the remaining ({@link #getUnarrivedParties})
1771N/A * parties arrive, the phase advances. The values returned by these
1771N/A * methods may reflect transient states and so are not in general
1771N/A * useful for synchronization control. Method {@link #toString}
1771N/A * returns snapshots of these state queries in a form convenient for
1771N/A * informal monitoring.
1771N/A *
1771N/A * <p><b>Sample usages:</b>
1771N/A *
1771N/A * <p>A {@code Phaser} may be used instead of a {@code CountDownLatch}
3387N/A * to control a one-shot action serving a variable number of parties.
3387N/A * The typical idiom is for the method setting this up to first
3387N/A * register, then start the actions, then deregister, as in:
1771N/A *
1771N/A * <pre> {@code
1771N/A * void runTasks(List<Runnable> tasks) {
1771N/A * final Phaser phaser = new Phaser(1); // "1" to register self
1771N/A * // create and start threads
4234N/A * for (final Runnable task : tasks) {
1771N/A * phaser.register();
1771N/A * new Thread() {
1771N/A * public void run() {
1771N/A * phaser.arriveAndAwaitAdvance(); // await all creation
1771N/A * task.run();
1771N/A * }
1771N/A * }.start();
1771N/A * }
1771N/A *
1771N/A * // allow threads to start and deregister self
1771N/A * phaser.arriveAndDeregister();
1771N/A * }}</pre>
1771N/A *
1771N/A * <p>One way to cause a set of threads to repeatedly perform actions
1771N/A * for a given number of iterations is to override {@code onAdvance}:
1771N/A *
1771N/A * <pre> {@code
1771N/A * void startTasks(List<Runnable> tasks, final int iterations) {
1771N/A * final Phaser phaser = new Phaser() {
1771N/A * protected boolean onAdvance(int phase, int registeredParties) {
1771N/A * return phase >= iterations || registeredParties == 0;
1771N/A * }
1771N/A * };
1771N/A * phaser.register();
1771N/A * for (final Runnable task : tasks) {
1771N/A * phaser.register();
1771N/A * new Thread() {
1771N/A * public void run() {
1771N/A * do {
1771N/A * task.run();
1771N/A * phaser.arriveAndAwaitAdvance();
1771N/A * } while (!phaser.isTerminated());
1771N/A * }
1771N/A * }.start();
1771N/A * }
1771N/A * phaser.arriveAndDeregister(); // deregister self, don't wait
1771N/A * }}</pre>
1771N/A *
1771N/A * If the main task must later await termination, it
1771N/A * may re-register and then execute a similar loop:
1771N/A * <pre> {@code
1771N/A * // ...
1771N/A * phaser.register();
1771N/A * while (!phaser.isTerminated())
1771N/A * phaser.arriveAndAwaitAdvance();}</pre>
1771N/A *
1771N/A * <p>Related constructions may be used to await particular phase numbers
1771N/A * in contexts where you are sure that the phase will never wrap around
1771N/A * {@code Integer.MAX_VALUE}. For example:
1771N/A *
1771N/A * <pre> {@code
1771N/A * void awaitPhase(Phaser phaser, int phase) {
1771N/A * int p = phaser.register(); // assumes caller not already registered
1771N/A * while (p < phase) {
1771N/A * if (phaser.isTerminated())
1771N/A * // ... deal with unexpected termination
1771N/A * else
1771N/A * p = phaser.arriveAndAwaitAdvance();
1771N/A * }
1771N/A * phaser.arriveAndDeregister();
1771N/A * }}</pre>
1771N/A *
1771N/A *
3387N/A * <p>To create a set of {@code n} tasks using a tree of phasers, you
3387N/A * could use code of the following form, assuming a Task class with a
3387N/A * constructor accepting a {@code Phaser} that it registers with upon
3387N/A * construction. After invocation of {@code build(new Task[n], 0, n,
3387N/A * new Phaser())}, these tasks could then be started, for example by
3387N/A * submitting to a pool:
1771N/A *
1771N/A * <pre> {@code
3387N/A * void build(Task[] tasks, int lo, int hi, Phaser ph) {
1771N/A * if (hi - lo > TASKS_PER_PHASER) {
1771N/A * for (int i = lo; i < hi; i += TASKS_PER_PHASER) {
1771N/A * int j = Math.min(i + TASKS_PER_PHASER, hi);
3387N/A * build(tasks, i, j, new Phaser(ph));
1771N/A * }
1771N/A * } else {
1771N/A * for (int i = lo; i < hi; ++i)
3387N/A * tasks[i] = new Task(ph);
1771N/A * // assumes new Task(ph) performs ph.register()
1771N/A * }
3387N/A * }}</pre>
1771N/A *
1771N/A * The best value of {@code TASKS_PER_PHASER} depends mainly on
3387N/A * expected synchronization rates. A value as low as four may
3387N/A * be appropriate for extremely small per-phase task bodies (thus
1771N/A * high rates), or up to hundreds for extremely large ones.
1771N/A *
1771N/A * <p><b>Implementation notes</b>: This implementation restricts the
1771N/A * maximum number of parties to 65535. Attempts to register additional
1771N/A * parties result in {@code IllegalStateException}. However, you can and
1771N/A * should create tiered phasers to accommodate arbitrarily large sets
1771N/A * of participants.
1771N/A *
1771N/A * @since 1.7
1771N/A * @author Doug Lea
1771N/A */
1771N/Apublic class Phaser {
1771N/A /*
1771N/A * This class implements an extension of X10 "clocks". Thanks to
1771N/A * Vijay Saraswat for the idea, and to Vivek Sarkar for
1771N/A * enhancements to extend functionality.
1771N/A */
1771N/A
1771N/A /**
3387N/A * Primary state representation, holding four bit-fields:
1771N/A *
3387N/A * unarrived -- the number of parties yet to hit barrier (bits 0-15)
3387N/A * parties -- the number of parties to wait (bits 16-31)
3387N/A * phase -- the generation of the barrier (bits 32-62)
3387N/A * terminated -- set if barrier is terminated (bit 63 / sign)
3387N/A *
3387N/A * Except that a phaser with no registered parties is
3387N/A * distinguished by the otherwise illegal state of having zero
3387N/A * parties and one unarrived parties (encoded as EMPTY below).
1771N/A *
3387N/A * To efficiently maintain atomicity, these values are packed into
3387N/A * a single (atomic) long. Good performance relies on keeping
3387N/A * state decoding and encoding simple, and keeping race windows
3387N/A * short.
1771N/A *
3387N/A * All state updates are performed via CAS except initial
3387N/A * registration of a sub-phaser (i.e., one with a non-null
3387N/A * parent). In this (relatively rare) case, we use built-in
3387N/A * synchronization to lock while first registering with its
3387N/A * parent.
3387N/A *
3387N/A * The phase of a subphaser is allowed to lag that of its
3387N/A * ancestors until it is actually accessed -- see method
3387N/A * reconcileState.
1771N/A */
1771N/A private volatile long state;
1771N/A
3387N/A private static final int MAX_PARTIES = 0xffff;
3387N/A private static final int MAX_PHASE = Integer.MAX_VALUE;
3387N/A private static final int PARTIES_SHIFT = 16;
3387N/A private static final int PHASE_SHIFT = 32;
3387N/A private static final int UNARRIVED_MASK = 0xffff; // to mask ints
3387N/A private static final long PARTIES_MASK = 0xffff0000L; // to mask longs
3387N/A private static final long TERMINATION_BIT = 1L << 63;
3387N/A
3387N/A // some special values
3387N/A private static final int ONE_ARRIVAL = 1;
3387N/A private static final int ONE_PARTY = 1 << PARTIES_SHIFT;
3387N/A private static final int EMPTY = 1;
3387N/A
3387N/A // The following unpacking methods are usually manually inlined
1771N/A
1771N/A private static int unarrivedOf(long s) {
3387N/A int counts = (int)s;
3387N/A return (counts == EMPTY) ? 0 : counts & UNARRIVED_MASK;
1771N/A }
1771N/A
1771N/A private static int partiesOf(long s) {
3387N/A return (int)s >>> PARTIES_SHIFT;
1771N/A }
1771N/A
1771N/A private static int phaseOf(long s) {
3387N/A return (int)(s >>> PHASE_SHIFT);
1771N/A }
1771N/A
1771N/A private static int arrivedOf(long s) {
3387N/A int counts = (int)s;
3387N/A return (counts == EMPTY) ? 0 :
3387N/A (counts >>> PARTIES_SHIFT) - (counts & UNARRIVED_MASK);
1771N/A }
1771N/A
1771N/A /**
1771N/A * The parent of this phaser, or null if none
1771N/A */
1771N/A private final Phaser parent;
1771N/A
1771N/A /**
3387N/A * The root of phaser tree. Equals this if not in a tree.
1771N/A */
1771N/A private final Phaser root;
1771N/A
1771N/A /**
1771N/A * Heads of Treiber stacks for waiting threads. To eliminate
3387N/A * contention when releasing some threads while adding others, we
1771N/A * use two of them, alternating across even and odd phases.
3387N/A * Subphasers share queues with root to speed up releases.
1771N/A */
3387N/A private final AtomicReference<QNode> evenQ;
3387N/A private final AtomicReference<QNode> oddQ;
1771N/A
1771N/A private AtomicReference<QNode> queueFor(int phase) {
1771N/A return ((phase & 1) == 0) ? evenQ : oddQ;
1771N/A }
1771N/A
1771N/A /**
3387N/A * Returns message string for bounds exceptions on arrival.
3387N/A */
3387N/A private String badArrive(long s) {
3387N/A return "Attempted arrival of unregistered party for " +
3387N/A stateToString(s);
3387N/A }
3387N/A
3387N/A /**
3387N/A * Returns message string for bounds exceptions on registration.
3387N/A */
3387N/A private String badRegister(long s) {
3387N/A return "Attempt to register more than " +
3387N/A MAX_PARTIES + " parties for " + stateToString(s);
3387N/A }
3387N/A
3387N/A /**
3387N/A * Main implementation for methods arrive and arriveAndDeregister.
3387N/A * Manually tuned to speed up and minimize race windows for the
3387N/A * common case of just decrementing unarrived field.
3387N/A *
3387N/A * @param deregister false for arrive, true for arriveAndDeregister
1771N/A */
3387N/A private int doArrive(boolean deregister) {
3387N/A int adj = deregister ? ONE_ARRIVAL|ONE_PARTY : ONE_ARRIVAL;
3387N/A final Phaser root = this.root;
3387N/A for (;;) {
3387N/A long s = (root == this) ? state : reconcileState();
3387N/A int phase = (int)(s >>> PHASE_SHIFT);
3387N/A int counts = (int)s;
3387N/A int unarrived = (counts & UNARRIVED_MASK) - 1;
3387N/A if (phase < 0)
3387N/A return phase;
3387N/A else if (counts == EMPTY || unarrived < 0) {
3387N/A if (root == this || reconcileState() == s)
3387N/A throw new IllegalStateException(badArrive(s));
3387N/A }
3387N/A else if (UNSAFE.compareAndSwapLong(this, stateOffset, s, s-=adj)) {
3387N/A if (unarrived == 0) {
3387N/A long n = s & PARTIES_MASK; // base of next state
3387N/A int nextUnarrived = (int)n >>> PARTIES_SHIFT;
3387N/A if (root != this)
3387N/A return parent.doArrive(nextUnarrived == 0);
3387N/A if (onAdvance(phase, nextUnarrived))
3387N/A n |= TERMINATION_BIT;
3387N/A else if (nextUnarrived == 0)
3387N/A n |= EMPTY;
3387N/A else
3387N/A n |= nextUnarrived;
3387N/A n |= (long)((phase + 1) & MAX_PHASE) << PHASE_SHIFT;
3387N/A UNSAFE.compareAndSwapLong(this, stateOffset, s, n);
3387N/A releaseWaiters(phase);
3387N/A }
3387N/A return phase;
3387N/A }
3387N/A }
1771N/A }
1771N/A
1771N/A /**
3387N/A * Implementation of register, bulkRegister
3387N/A *
3387N/A * @param registrations number to add to both parties and
3387N/A * unarrived fields. Must be greater than zero.
1771N/A */
3387N/A private int doRegister(int registrations) {
3387N/A // adjustment to state
3387N/A long adj = ((long)registrations << PARTIES_SHIFT) | registrations;
3387N/A final Phaser parent = this.parent;
3387N/A int phase;
3387N/A for (;;) {
3387N/A long s = state;
3387N/A int counts = (int)s;
3387N/A int parties = counts >>> PARTIES_SHIFT;
3387N/A int unarrived = counts & UNARRIVED_MASK;
3387N/A if (registrations > MAX_PARTIES - parties)
3387N/A throw new IllegalStateException(badRegister(s));
3387N/A else if ((phase = (int)(s >>> PHASE_SHIFT)) < 0)
3387N/A break;
3387N/A else if (counts != EMPTY) { // not 1st registration
3387N/A if (parent == null || reconcileState() == s) {
3387N/A if (unarrived == 0) // wait out advance
3387N/A root.internalAwaitAdvance(phase, null);
3387N/A else if (UNSAFE.compareAndSwapLong(this, stateOffset,
3387N/A s, s + adj))
3387N/A break;
3387N/A }
3387N/A }
3387N/A else if (parent == null) { // 1st root registration
3387N/A long next = ((long)phase << PHASE_SHIFT) | adj;
3387N/A if (UNSAFE.compareAndSwapLong(this, stateOffset, s, next))
3387N/A break;
3387N/A }
3387N/A else {
3387N/A synchronized (this) { // 1st sub registration
3387N/A if (state == s) { // recheck under lock
3387N/A parent.doRegister(1);
3387N/A do { // force current phase
3387N/A phase = (int)(root.state >>> PHASE_SHIFT);
3387N/A // assert phase < 0 || (int)state == EMPTY;
3387N/A } while (!UNSAFE.compareAndSwapLong
3387N/A (this, stateOffset, state,
3387N/A ((long)phase << PHASE_SHIFT) | adj));
3387N/A break;
1771N/A }
1771N/A }
1771N/A }
1771N/A }
3387N/A return phase;
3387N/A }
3387N/A
3387N/A /**
3387N/A * Resolves lagged phase propagation from root if necessary.
3387N/A * Reconciliation normally occurs when root has advanced but
3387N/A * subphasers have not yet done so, in which case they must finish
3387N/A * their own advance by setting unarrived to parties (or if
3387N/A * parties is zero, resetting to unregistered EMPTY state).
3387N/A * However, this method may also be called when "floating"
3387N/A * subphasers with possibly some unarrived parties are merely
3387N/A * catching up to current phase, in which case counts are
3387N/A * unaffected.
3387N/A *
3387N/A * @return reconciled state
3387N/A */
3387N/A private long reconcileState() {
3387N/A final Phaser root = this.root;
3387N/A long s = state;
3387N/A if (root != this) {
3387N/A int phase, u, p;
3387N/A // CAS root phase with current parties; possibly trip unarrived
3387N/A while ((phase = (int)(root.state >>> PHASE_SHIFT)) !=
3387N/A (int)(s >>> PHASE_SHIFT) &&
3387N/A !UNSAFE.compareAndSwapLong
3387N/A (this, stateOffset, s,
3387N/A s = (((long)phase << PHASE_SHIFT) |
3387N/A (s & PARTIES_MASK) |
3387N/A ((p = (int)s >>> PARTIES_SHIFT) == 0 ? EMPTY :
3387N/A (u = (int)s & UNARRIVED_MASK) == 0 ? p : u))))
3387N/A s = state;
3387N/A }
1771N/A return s;
1771N/A }
1771N/A
1771N/A /**
3387N/A * Creates a new phaser with no initially registered parties, no
3387N/A * parent, and initial phase number 0. Any thread using this
1771N/A * phaser will need to first register for it.
1771N/A */
1771N/A public Phaser() {
3387N/A this(null, 0);
1771N/A }
1771N/A
1771N/A /**
3387N/A * Creates a new phaser with the given number of registered
3387N/A * unarrived parties, no parent, and initial phase number 0.
1771N/A *
3387N/A * @param parties the number of parties required to advance to the
3387N/A * next phase
1771N/A * @throws IllegalArgumentException if parties less than zero
1771N/A * or greater than the maximum number of parties supported
1771N/A */
1771N/A public Phaser(int parties) {
1771N/A this(null, parties);
1771N/A }
1771N/A
1771N/A /**
3387N/A * Equivalent to {@link #Phaser(Phaser, int) Phaser(parent, 0)}.
1771N/A *
1771N/A * @param parent the parent phaser
1771N/A */
1771N/A public Phaser(Phaser parent) {
3387N/A this(parent, 0);
1771N/A }
1771N/A
1771N/A /**
3387N/A * Creates a new phaser with the given parent and number of
3387N/A * registered unarrived parties. When the given parent is non-null
3387N/A * and the given number of parties is greater than zero, this
3387N/A * child phaser is registered with its parent.
1771N/A *
1771N/A * @param parent the parent phaser
3387N/A * @param parties the number of parties required to advance to the
3387N/A * next phase
1771N/A * @throws IllegalArgumentException if parties less than zero
1771N/A * or greater than the maximum number of parties supported
1771N/A */
1771N/A public Phaser(Phaser parent, int parties) {
3387N/A if (parties >>> PARTIES_SHIFT != 0)
1771N/A throw new IllegalArgumentException("Illegal number of parties");
1771N/A int phase = 0;
1771N/A this.parent = parent;
1771N/A if (parent != null) {
3387N/A final Phaser root = parent.root;
3387N/A this.root = root;
3387N/A this.evenQ = root.evenQ;
3387N/A this.oddQ = root.oddQ;
3387N/A if (parties != 0)
3387N/A phase = parent.doRegister(1);
1771N/A }
3387N/A else {
1771N/A this.root = this;
3387N/A this.evenQ = new AtomicReference<QNode>();
3387N/A this.oddQ = new AtomicReference<QNode>();
3387N/A }
3387N/A this.state = (parties == 0) ? (long)EMPTY :
3387N/A ((long)phase << PHASE_SHIFT) |
3387N/A ((long)parties << PARTIES_SHIFT) |
3387N/A ((long)parties);
1771N/A }
1771N/A
1771N/A /**
3387N/A * Adds a new unarrived party to this phaser. If an ongoing
3387N/A * invocation of {@link #onAdvance} is in progress, this method
3387N/A * may await its completion before returning. If this phaser has
3387N/A * a parent, and this phaser previously had no registered parties,
3387N/A * this child phaser is also registered with its parent. If
3387N/A * this phaser is terminated, the attempt to register has
3387N/A * no effect, and a negative value is returned.
1771N/A *
3387N/A * @return the arrival phase number to which this registration
3387N/A * applied. If this value is negative, then this phaser has
3387N/A * terminated, in which case registration has no effect.
1771N/A * @throws IllegalStateException if attempting to register more
1771N/A * than the maximum supported number of parties
1771N/A */
1771N/A public int register() {
1771N/A return doRegister(1);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Adds the given number of new unarrived parties to this phaser.
3387N/A * If an ongoing invocation of {@link #onAdvance} is in progress,
3387N/A * this method may await its completion before returning. If this
3387N/A * phaser has a parent, and the given number of parties is greater
3387N/A * than zero, and this phaser previously had no registered
3387N/A * parties, this child phaser is also registered with its parent.
3387N/A * If this phaser is terminated, the attempt to register has no
3387N/A * effect, and a negative value is returned.
1771N/A *
3387N/A * @param parties the number of additional parties required to
3387N/A * advance to the next phase
3387N/A * @return the arrival phase number to which this registration
3387N/A * applied. If this value is negative, then this phaser has
3387N/A * terminated, in which case registration has no effect.
1771N/A * @throws IllegalStateException if attempting to register more
1771N/A * than the maximum supported number of parties
3387N/A * @throws IllegalArgumentException if {@code parties < 0}
1771N/A */
1771N/A public int bulkRegister(int parties) {
1771N/A if (parties < 0)
1771N/A throw new IllegalArgumentException();
1771N/A if (parties == 0)
1771N/A return getPhase();
1771N/A return doRegister(parties);
1771N/A }
1771N/A
1771N/A /**
3387N/A * Arrives at this phaser, without waiting for others to arrive.
3387N/A *
3387N/A * <p>It is a usage error for an unregistered party to invoke this
3387N/A * method. However, this error may result in an {@code
3387N/A * IllegalStateException} only upon some subsequent operation on
3387N/A * this phaser, if ever.
1771N/A *
1771N/A * @return the arrival phase number, or a negative value if terminated
1771N/A * @throws IllegalStateException if not terminated and the number
1771N/A * of unarrived parties would become negative
1771N/A */
1771N/A public int arrive() {
3387N/A return doArrive(false);
1771N/A }
1771N/A
1771N/A /**
3387N/A * Arrives at this phaser and deregisters from it without waiting
3387N/A * for others to arrive. Deregistration reduces the number of
3387N/A * parties required to advance in future phases. If this phaser
1771N/A * has a parent, and deregistration causes this phaser to have
3387N/A * zero parties, this phaser is also deregistered from its parent.
3387N/A *
3387N/A * <p>It is a usage error for an unregistered party to invoke this
3387N/A * method. However, this error may result in an {@code
3387N/A * IllegalStateException} only upon some subsequent operation on
3387N/A * this phaser, if ever.
1771N/A *
1771N/A * @return the arrival phase number, or a negative value if terminated
1771N/A * @throws IllegalStateException if not terminated and the number
1771N/A * of registered or unarrived parties would become negative
1771N/A */
1771N/A public int arriveAndDeregister() {
3387N/A return doArrive(true);
1771N/A }
1771N/A
1771N/A /**
3387N/A * Arrives at this phaser and awaits others. Equivalent in effect
1771N/A * to {@code awaitAdvance(arrive())}. If you need to await with
1771N/A * interruption or timeout, you can arrange this with an analogous
3387N/A * construction using one of the other forms of the {@code
3387N/A * awaitAdvance} method. If instead you need to deregister upon
3387N/A * arrival, use {@code awaitAdvance(arriveAndDeregister())}.
1771N/A *
3387N/A * <p>It is a usage error for an unregistered party to invoke this
3387N/A * method. However, this error may result in an {@code
3387N/A * IllegalStateException} only upon some subsequent operation on
3387N/A * this phaser, if ever.
3387N/A *
3387N/A * @return the arrival phase number, or the (negative)
3387N/A * {@linkplain #getPhase() current phase} if terminated
1771N/A * @throws IllegalStateException if not terminated and the number
1771N/A * of unarrived parties would become negative
1771N/A */
1771N/A public int arriveAndAwaitAdvance() {
3387N/A // Specialization of doArrive+awaitAdvance eliminating some reads/paths
3387N/A final Phaser root = this.root;
3387N/A for (;;) {
3387N/A long s = (root == this) ? state : reconcileState();
3387N/A int phase = (int)(s >>> PHASE_SHIFT);
3387N/A int counts = (int)s;
3387N/A int unarrived = (counts & UNARRIVED_MASK) - 1;
3387N/A if (phase < 0)
3387N/A return phase;
3387N/A else if (counts == EMPTY || unarrived < 0) {
3387N/A if (reconcileState() == s)
3387N/A throw new IllegalStateException(badArrive(s));
3387N/A }
3387N/A else if (UNSAFE.compareAndSwapLong(this, stateOffset, s,
3387N/A s -= ONE_ARRIVAL)) {
3387N/A if (unarrived != 0)
3387N/A return root.internalAwaitAdvance(phase, null);
3387N/A if (root != this)
3387N/A return parent.arriveAndAwaitAdvance();
3387N/A long n = s & PARTIES_MASK; // base of next state
3387N/A int nextUnarrived = (int)n >>> PARTIES_SHIFT;
3387N/A if (onAdvance(phase, nextUnarrived))
3387N/A n |= TERMINATION_BIT;
3387N/A else if (nextUnarrived == 0)
3387N/A n |= EMPTY;
3387N/A else
3387N/A n |= nextUnarrived;
3387N/A int nextPhase = (phase + 1) & MAX_PHASE;
3387N/A n |= (long)nextPhase << PHASE_SHIFT;
3387N/A if (!UNSAFE.compareAndSwapLong(this, stateOffset, s, n))
3387N/A return (int)(state >>> PHASE_SHIFT); // terminated
3387N/A releaseWaiters(phase);
3387N/A return nextPhase;
3387N/A }
3387N/A }
1771N/A }
1771N/A
1771N/A /**
3387N/A * Awaits the phase of this phaser to advance from the given phase
3387N/A * value, returning immediately if the current phase is not equal
3387N/A * to the given phase value or this phaser is terminated.
1771N/A *
1771N/A * @param phase an arrival phase number, or negative value if
1771N/A * terminated; this argument is normally the value returned by a
3387N/A * previous call to {@code arrive} or {@code arriveAndDeregister}.
3387N/A * @return the next arrival phase number, or the argument if it is
3387N/A * negative, or the (negative) {@linkplain #getPhase() current phase}
3387N/A * if terminated
1771N/A */
1771N/A public int awaitAdvance(int phase) {
3387N/A final Phaser root = this.root;
3387N/A long s = (root == this) ? state : reconcileState();
3387N/A int p = (int)(s >>> PHASE_SHIFT);
1771N/A if (phase < 0)
1771N/A return phase;
3387N/A if (p == phase)
3387N/A return root.internalAwaitAdvance(phase, null);
3387N/A return p;
1771N/A }
1771N/A
1771N/A /**
3387N/A * Awaits the phase of this phaser to advance from the given phase
1771N/A * value, throwing {@code InterruptedException} if interrupted
3387N/A * while waiting, or returning immediately if the current phase is
3387N/A * not equal to the given phase value or this phaser is
3387N/A * terminated.
1771N/A *
1771N/A * @param phase an arrival phase number, or negative value if
1771N/A * terminated; this argument is normally the value returned by a
3387N/A * previous call to {@code arrive} or {@code arriveAndDeregister}.
3387N/A * @return the next arrival phase number, or the argument if it is
3387N/A * negative, or the (negative) {@linkplain #getPhase() current phase}
3387N/A * if terminated
1771N/A * @throws InterruptedException if thread interrupted while waiting
1771N/A */
1771N/A public int awaitAdvanceInterruptibly(int phase)
1771N/A throws InterruptedException {
3387N/A final Phaser root = this.root;
3387N/A long s = (root == this) ? state : reconcileState();
3387N/A int p = (int)(s >>> PHASE_SHIFT);
1771N/A if (phase < 0)
1771N/A return phase;
3387N/A if (p == phase) {
3387N/A QNode node = new QNode(this, phase, true, false, 0L);
3387N/A p = root.internalAwaitAdvance(phase, node);
3387N/A if (node.wasInterrupted)
3387N/A throw new InterruptedException();
3387N/A }
3387N/A return p;
1771N/A }
1771N/A
1771N/A /**
3387N/A * Awaits the phase of this phaser to advance from the given phase
1771N/A * value or the given timeout to elapse, throwing {@code
1771N/A * InterruptedException} if interrupted while waiting, or
3387N/A * returning immediately if the current phase is not equal to the
3387N/A * given phase value or this phaser is terminated.
1771N/A *
1771N/A * @param phase an arrival phase number, or negative value if
1771N/A * terminated; this argument is normally the value returned by a
3387N/A * previous call to {@code arrive} or {@code arriveAndDeregister}.
1771N/A * @param timeout how long to wait before giving up, in units of
1771N/A * {@code unit}
1771N/A * @param unit a {@code TimeUnit} determining how to interpret the
1771N/A * {@code timeout} parameter
3387N/A * @return the next arrival phase number, or the argument if it is
3387N/A * negative, or the (negative) {@linkplain #getPhase() current phase}
3387N/A * if terminated
1771N/A * @throws InterruptedException if thread interrupted while waiting
1771N/A * @throws TimeoutException if timed out while waiting
1771N/A */
1771N/A public int awaitAdvanceInterruptibly(int phase,
1771N/A long timeout, TimeUnit unit)
1771N/A throws InterruptedException, TimeoutException {
3387N/A long nanos = unit.toNanos(timeout);
3387N/A final Phaser root = this.root;
3387N/A long s = (root == this) ? state : reconcileState();
3387N/A int p = (int)(s >>> PHASE_SHIFT);
1771N/A if (phase < 0)
1771N/A return phase;
3387N/A if (p == phase) {
3387N/A QNode node = new QNode(this, phase, true, true, nanos);
3387N/A p = root.internalAwaitAdvance(phase, node);
3387N/A if (node.wasInterrupted)
3387N/A throw new InterruptedException();
3387N/A else if (p == phase)
3387N/A throw new TimeoutException();
3387N/A }
3387N/A return p;
1771N/A }
1771N/A
1771N/A /**
3387N/A * Forces this phaser to enter termination state. Counts of
3387N/A * registered parties are unaffected. If this phaser is a member
3387N/A * of a tiered set of phasers, then all of the phasers in the set
3387N/A * are terminated. If this phaser is already terminated, this
3387N/A * method has no effect. This method may be useful for
3387N/A * coordinating recovery after one or more tasks encounter
1771N/A * unexpected exceptions.
1771N/A */
1771N/A public void forceTermination() {
3387N/A // Only need to change root state
3387N/A final Phaser root = this.root;
3387N/A long s;
3387N/A while ((s = root.state) >= 0) {
3387N/A if (UNSAFE.compareAndSwapLong(root, stateOffset,
3387N/A s, s | TERMINATION_BIT)) {
3387N/A // signal all threads
1771N/A releaseWaiters(0);
1771N/A releaseWaiters(1);
1771N/A return;
1771N/A }
1771N/A }
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the current phase number. The maximum phase number is
1771N/A * {@code Integer.MAX_VALUE}, after which it restarts at
3387N/A * zero. Upon termination, the phase number is negative,
3387N/A * in which case the prevailing phase prior to termination
3387N/A * may be obtained via {@code getPhase() + Integer.MIN_VALUE}.
1771N/A *
1771N/A * @return the phase number, or a negative value if terminated
1771N/A */
1771N/A public final int getPhase() {
3387N/A return (int)(root.state >>> PHASE_SHIFT);
1771N/A }
1771N/A
1771N/A /**
3387N/A * Returns the number of parties registered at this phaser.
1771N/A *
1771N/A * @return the number of parties
1771N/A */
1771N/A public int getRegisteredParties() {
1771N/A return partiesOf(state);
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the number of registered parties that have arrived at
3387N/A * the current phase of this phaser. If this phaser has terminated,
3387N/A * the returned value is meaningless and arbitrary.
1771N/A *
1771N/A * @return the number of arrived parties
1771N/A */
1771N/A public int getArrivedParties() {
3387N/A return arrivedOf(reconcileState());
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the number of registered parties that have not yet
3387N/A * arrived at the current phase of this phaser. If this phaser has
3387N/A * terminated, the returned value is meaningless and arbitrary.
1771N/A *
1771N/A * @return the number of unarrived parties
1771N/A */
1771N/A public int getUnarrivedParties() {
3387N/A return unarrivedOf(reconcileState());
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the parent of this phaser, or {@code null} if none.
1771N/A *
1771N/A * @return the parent of this phaser, or {@code null} if none
1771N/A */
1771N/A public Phaser getParent() {
1771N/A return parent;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns the root ancestor of this phaser, which is the same as
1771N/A * this phaser if it has no parent.
1771N/A *
1771N/A * @return the root ancestor of this phaser
1771N/A */
1771N/A public Phaser getRoot() {
1771N/A return root;
1771N/A }
1771N/A
1771N/A /**
3387N/A * Returns {@code true} if this phaser has been terminated.
1771N/A *
3387N/A * @return {@code true} if this phaser has been terminated
1771N/A */
1771N/A public boolean isTerminated() {
3387N/A return root.state < 0L;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Overridable method to perform an action upon impending phase
1771N/A * advance, and to control termination. This method is invoked
3387N/A * upon arrival of the party advancing this phaser (when all other
1771N/A * waiting parties are dormant). If this method returns {@code
3387N/A * true}, this phaser will be set to a final termination state
3387N/A * upon advance, and subsequent calls to {@link #isTerminated}
3387N/A * will return true. Any (unchecked) Exception or Error thrown by
3387N/A * an invocation of this method is propagated to the party
3387N/A * attempting to advance this phaser, in which case no advance
3387N/A * occurs.
1771N/A *
1771N/A * <p>The arguments to this method provide the state of the phaser
3387N/A * prevailing for the current transition. The effects of invoking
3387N/A * arrival, registration, and waiting methods on this phaser from
3387N/A * within {@code onAdvance} are unspecified and should not be
3387N/A * relied on.
1771N/A *
3387N/A * <p>If this phaser is a member of a tiered set of phasers, then
3387N/A * {@code onAdvance} is invoked only for its root phaser on each
3387N/A * advance.
1771N/A *
3387N/A * <p>To support the most common use cases, the default
3387N/A * implementation of this method returns {@code true} when the
3387N/A * number of registered parties has become zero as the result of a
3387N/A * party invoking {@code arriveAndDeregister}. You can disable
3387N/A * this behavior, thus enabling continuation upon future
3387N/A * registrations, by overriding this method to always return
3387N/A * {@code false}:
1771N/A *
3387N/A * <pre> {@code
3387N/A * Phaser phaser = new Phaser() {
3387N/A * protected boolean onAdvance(int phase, int parties) { return false; }
3387N/A * }}</pre>
3387N/A *
3387N/A * @param phase the current phase number on entry to this method,
3387N/A * before this phaser is advanced
1771N/A * @param registeredParties the current number of registered parties
3387N/A * @return {@code true} if this phaser should terminate
1771N/A */
1771N/A protected boolean onAdvance(int phase, int registeredParties) {
3387N/A return registeredParties == 0;
1771N/A }
1771N/A
1771N/A /**
1771N/A * Returns a string identifying this phaser, as well as its
1771N/A * state. The state, in brackets, includes the String {@code
1771N/A * "phase = "} followed by the phase number, {@code "parties = "}
1771N/A * followed by the number of registered parties, and {@code
1771N/A * "arrived = "} followed by the number of arrived parties.
1771N/A *
3387N/A * @return a string identifying this phaser, as well as its state
1771N/A */
1771N/A public String toString() {
3387N/A return stateToString(reconcileState());
3387N/A }
3387N/A
3387N/A /**
3387N/A * Implementation of toString and string-based error messages
3387N/A */
3387N/A private String stateToString(long s) {
1771N/A return super.toString() +
1771N/A "[phase = " + phaseOf(s) +
1771N/A " parties = " + partiesOf(s) +
1771N/A " arrived = " + arrivedOf(s) + "]";
1771N/A }
1771N/A
3387N/A // Waiting mechanics
3387N/A
3387N/A /**
3387N/A * Removes and signals threads from queue for phase.
3387N/A */
3387N/A private void releaseWaiters(int phase) {
3387N/A QNode q; // first element of queue
3387N/A Thread t; // its thread
3387N/A AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
3387N/A while ((q = head.get()) != null &&
3387N/A q.phase != (int)(root.state >>> PHASE_SHIFT)) {
3387N/A if (head.compareAndSet(q, q.next) &&
3387N/A (t = q.thread) != null) {
3387N/A q.thread = null;
3387N/A LockSupport.unpark(t);
3387N/A }
3387N/A }
3387N/A }
3387N/A
3387N/A /**
3387N/A * Variant of releaseWaiters that additionally tries to remove any
3387N/A * nodes no longer waiting for advance due to timeout or
3387N/A * interrupt. Currently, nodes are removed only if they are at
3387N/A * head of queue, which suffices to reduce memory footprint in
3387N/A * most usages.
3387N/A *
3387N/A * @return current phase on exit
3387N/A */
3387N/A private int abortWait(int phase) {
3387N/A AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
3387N/A for (;;) {
3387N/A Thread t;
3387N/A QNode q = head.get();
3387N/A int p = (int)(root.state >>> PHASE_SHIFT);
3387N/A if (q == null || ((t = q.thread) != null && q.phase == p))
3387N/A return p;
3387N/A if (head.compareAndSet(q, q.next) && t != null) {
3387N/A q.thread = null;
3387N/A LockSupport.unpark(t);
3387N/A }
3387N/A }
3387N/A }
3387N/A
3387N/A /** The number of CPUs, for spin control */
3387N/A private static final int NCPU = Runtime.getRuntime().availableProcessors();
3387N/A
3387N/A /**
3387N/A * The number of times to spin before blocking while waiting for
3387N/A * advance, per arrival while waiting. On multiprocessors, fully
3387N/A * blocking and waking up a large number of threads all at once is
3387N/A * usually a very slow process, so we use rechargeable spins to
3387N/A * avoid it when threads regularly arrive: When a thread in
3387N/A * internalAwaitAdvance notices another arrival before blocking,
3387N/A * and there appear to be enough CPUs available, it spins
3387N/A * SPINS_PER_ARRIVAL more times before blocking. The value trades
3387N/A * off good-citizenship vs big unnecessary slowdowns.
3387N/A */
3387N/A static final int SPINS_PER_ARRIVAL = (NCPU < 2) ? 1 : 1 << 8;
3387N/A
3387N/A /**
3387N/A * Possibly blocks and waits for phase to advance unless aborted.
3387N/A * Call only from root node.
3387N/A *
3387N/A * @param phase current phase
3387N/A * @param node if non-null, the wait node to track interrupt and timeout;
3387N/A * if null, denotes noninterruptible wait
3387N/A * @return current phase
3387N/A */
3387N/A private int internalAwaitAdvance(int phase, QNode node) {
3387N/A releaseWaiters(phase-1); // ensure old queue clean
3387N/A boolean queued = false; // true when node is enqueued
3387N/A int lastUnarrived = 0; // to increase spins upon change
3387N/A int spins = SPINS_PER_ARRIVAL;
3387N/A long s;
3387N/A int p;
3387N/A while ((p = (int)((s = state) >>> PHASE_SHIFT)) == phase) {
3387N/A if (node == null) { // spinning in noninterruptible mode
3387N/A int unarrived = (int)s & UNARRIVED_MASK;
3387N/A if (unarrived != lastUnarrived &&
3387N/A (lastUnarrived = unarrived) < NCPU)
3387N/A spins += SPINS_PER_ARRIVAL;
3387N/A boolean interrupted = Thread.interrupted();
3387N/A if (interrupted || --spins < 0) { // need node to record intr
3387N/A node = new QNode(this, phase, false, false, 0L);
3387N/A node.wasInterrupted = interrupted;
3387N/A }
3387N/A }
3387N/A else if (node.isReleasable()) // done or aborted
3387N/A break;
3387N/A else if (!queued) { // push onto queue
3387N/A AtomicReference<QNode> head = (phase & 1) == 0 ? evenQ : oddQ;
3387N/A QNode q = node.next = head.get();
3387N/A if ((q == null || q.phase == phase) &&
3387N/A (int)(state >>> PHASE_SHIFT) == phase) // avoid stale enq
3387N/A queued = head.compareAndSet(q, node);
3387N/A }
3387N/A else {
3387N/A try {
3387N/A ForkJoinPool.managedBlock(node);
3387N/A } catch (InterruptedException ie) {
3387N/A node.wasInterrupted = true;
3387N/A }
3387N/A }
3387N/A }
3387N/A
3387N/A if (node != null) {
3387N/A if (node.thread != null)
3387N/A node.thread = null; // avoid need for unpark()
3387N/A if (node.wasInterrupted && !node.interruptible)
3387N/A Thread.currentThread().interrupt();
3387N/A if (p == phase && (p = (int)(state >>> PHASE_SHIFT)) == phase)
3387N/A return abortWait(phase); // possibly clean up on abort
3387N/A }
3387N/A releaseWaiters(phase);
3387N/A return p;
3387N/A }
1771N/A
1771N/A /**
1771N/A * Wait nodes for Treiber stack representing wait queue
1771N/A */
1771N/A static final class QNode implements ForkJoinPool.ManagedBlocker {
1771N/A final Phaser phaser;
1771N/A final int phase;
3387N/A final boolean interruptible;
1771N/A final boolean timed;
3387N/A boolean wasInterrupted;
3387N/A long nanos;
3387N/A long lastTime;
1771N/A volatile Thread thread; // nulled to cancel wait
1771N/A QNode next;
3387N/A
1771N/A QNode(Phaser phaser, int phase, boolean interruptible,
3387N/A boolean timed, long nanos) {
1771N/A this.phaser = phaser;
1771N/A this.phase = phase;
3387N/A this.interruptible = interruptible;
3387N/A this.nanos = nanos;
1771N/A this.timed = timed;
3387N/A this.lastTime = timed ? System.nanoTime() : 0L;
1771N/A thread = Thread.currentThread();
1771N/A }
1771N/A
3387N/A public boolean isReleasable() {
3387N/A if (thread == null)
3387N/A return true;
3387N/A if (phaser.getPhase() != phase) {
3387N/A thread = null;
3387N/A return true;
3387N/A }
3387N/A if (Thread.interrupted())
3387N/A wasInterrupted = true;
3387N/A if (wasInterrupted && interruptible) {
3387N/A thread = null;
3387N/A return true;
3387N/A }
3387N/A if (timed) {
3387N/A if (nanos > 0L) {
3387N/A long now = System.nanoTime();
3387N/A nanos -= now - lastTime;
3387N/A lastTime = now;
3387N/A }
3387N/A if (nanos <= 0L) {
3387N/A thread = null;
3387N/A return true;
3387N/A }
3387N/A }
3387N/A return false;
1771N/A }
1771N/A
3387N/A public boolean block() {
3387N/A if (isReleasable())
3387N/A return true;
3387N/A else if (!timed)
3387N/A LockSupport.park(this);
3387N/A else if (nanos > 0)
3387N/A LockSupport.parkNanos(this, nanos);
3387N/A return isReleasable();
1771N/A }
1771N/A }
1771N/A
1771N/A // Unsafe mechanics
1771N/A
3647N/A private static final sun.misc.Unsafe UNSAFE;
3647N/A private static final long stateOffset;
3647N/A static {
1771N/A try {
3647N/A UNSAFE = sun.misc.Unsafe.getUnsafe();
3647N/A Class k = Phaser.class;
3647N/A stateOffset = UNSAFE.objectFieldOffset
3647N/A (k.getDeclaredField("state"));
3647N/A } catch (Exception e) {
3647N/A throw new Error(e);
1771N/A }
1771N/A }
1771N/A}