jaroslav@1890: /* jaroslav@1890: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1890: * jaroslav@1890: * This code is free software; you can redistribute it and/or modify it jaroslav@1890: * under the terms of the GNU General Public License version 2 only, as jaroslav@1890: * published by the Free Software Foundation. Oracle designates this jaroslav@1890: * particular file as subject to the "Classpath" exception as provided jaroslav@1890: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1890: * jaroslav@1890: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1890: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1890: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1890: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1890: * accompanied this code). jaroslav@1890: * jaroslav@1890: * You should have received a copy of the GNU General Public License version jaroslav@1890: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1890: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1890: * jaroslav@1890: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1890: * or visit www.oracle.com if you need additional information or have any jaroslav@1890: * questions. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * This file is available under and governed by the GNU General Public jaroslav@1890: * License version 2 only, as published by the Free Software Foundation. jaroslav@1890: * However, the following notice accompanied the original version of this jaroslav@1890: * file: jaroslav@1890: * jaroslav@1890: * Written by Doug Lea with assistance from members of JCP JSR-166 jaroslav@1890: * Expert Group and released to the public domain, as explained at jaroslav@1890: * http://creativecommons.org/publicdomain/zero/1.0/ jaroslav@1890: */ jaroslav@1890: jaroslav@1890: package java.util.concurrent.locks; jaroslav@1890: import java.util.*; jaroslav@1890: import java.util.concurrent.*; jaroslav@1890: import java.util.concurrent.atomic.*; jaroslav@1890: import sun.misc.Unsafe; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Provides a framework for implementing blocking locks and related jaroslav@1890: * synchronizers (semaphores, events, etc) that rely on jaroslav@1890: * first-in-first-out (FIFO) wait queues. This class is designed to jaroslav@1890: * be a useful basis for most kinds of synchronizers that rely on a jaroslav@1890: * single atomic int value to represent state. Subclasses jaroslav@1890: * must define the protected methods that change this state, and which jaroslav@1890: * define what that state means in terms of this object being acquired jaroslav@1890: * or released. Given these, the other methods in this class carry jaroslav@1890: * out all queuing and blocking mechanics. Subclasses can maintain jaroslav@1890: * other state fields, but only the atomically updated int jaroslav@1890: * value manipulated using methods {@link #getState}, {@link jaroslav@1890: * #setState} and {@link #compareAndSetState} is tracked with respect jaroslav@1890: * to synchronization. jaroslav@1890: * jaroslav@1890: *
Subclasses should be defined as non-public internal helper jaroslav@1890: * classes that are used to implement the synchronization properties jaroslav@1890: * of their enclosing class. Class jaroslav@1890: * AbstractQueuedSynchronizer does not implement any jaroslav@1890: * synchronization interface. Instead it defines methods such as jaroslav@1890: * {@link #acquireInterruptibly} that can be invoked as jaroslav@1890: * appropriate by concrete locks and related synchronizers to jaroslav@1890: * implement their public methods. jaroslav@1890: * jaroslav@1890: *
This class supports either or both a default exclusive jaroslav@1890: * mode and a shared mode. When acquired in exclusive mode, jaroslav@1890: * attempted acquires by other threads cannot succeed. Shared mode jaroslav@1890: * acquires by multiple threads may (but need not) succeed. This class jaroslav@1890: * does not "understand" these differences except in the jaroslav@1890: * mechanical sense that when a shared mode acquire succeeds, the next jaroslav@1890: * waiting thread (if one exists) must also determine whether it can jaroslav@1890: * acquire as well. Threads waiting in the different modes share the jaroslav@1890: * same FIFO queue. Usually, implementation subclasses support only jaroslav@1890: * one of these modes, but both can come into play for example in a jaroslav@1890: * {@link ReadWriteLock}. Subclasses that support only exclusive or jaroslav@1890: * only shared modes need not define the methods supporting the unused mode. jaroslav@1890: * jaroslav@1890: *
This class defines a nested {@link ConditionObject} class that jaroslav@1890: * can be used as a {@link Condition} implementation by subclasses jaroslav@1890: * supporting exclusive mode for which method {@link jaroslav@1890: * #isHeldExclusively} reports whether synchronization is exclusively jaroslav@1890: * held with respect to the current thread, method {@link #release} jaroslav@1890: * invoked with the current {@link #getState} value fully releases jaroslav@1890: * this object, and {@link #acquire}, given this saved state value, jaroslav@1890: * eventually restores this object to its previous acquired state. No jaroslav@1890: * AbstractQueuedSynchronizer method otherwise creates such a jaroslav@1890: * condition, so if this constraint cannot be met, do not use it. The jaroslav@1890: * behavior of {@link ConditionObject} depends of course on the jaroslav@1890: * semantics of its synchronizer implementation. jaroslav@1890: * jaroslav@1890: *
This class provides inspection, instrumentation, and monitoring jaroslav@1890: * methods for the internal queue, as well as similar methods for jaroslav@1890: * condition objects. These can be exported as desired into classes jaroslav@1890: * using an AbstractQueuedSynchronizer for their jaroslav@1890: * synchronization mechanics. jaroslav@1890: * jaroslav@1890: *
Serialization of this class stores only the underlying atomic jaroslav@1890: * integer maintaining state, so deserialized objects have empty jaroslav@1890: * thread queues. Typical subclasses requiring serializability will jaroslav@1890: * define a readObject method that restores this to a known jaroslav@1890: * initial state upon deserialization. jaroslav@1890: * jaroslav@1890: *
To use this class as the basis of a synchronizer, redefine the jaroslav@1890: * following methods, as applicable, by inspecting and/or modifying jaroslav@1890: * the synchronization state using {@link #getState}, {@link jaroslav@1890: * #setState} and/or {@link #compareAndSetState}: jaroslav@1890: * jaroslav@1890: *
You may also find the inherited methods from {@link jaroslav@1890: * AbstractOwnableSynchronizer} useful to keep track of the thread jaroslav@1890: * owning an exclusive synchronizer. You are encouraged to use them jaroslav@1890: * -- this enables monitoring and diagnostic tools to assist users in jaroslav@1890: * determining which threads hold locks. jaroslav@1890: * jaroslav@1890: *
Even though this class is based on an internal FIFO queue, it jaroslav@1890: * does not automatically enforce FIFO acquisition policies. The core jaroslav@1890: * of exclusive synchronization takes the form: jaroslav@1890: * jaroslav@1890: *
jaroslav@1890: * Acquire: jaroslav@1890: * while (!tryAcquire(arg)) { jaroslav@1890: * enqueue thread if it is not already queued; jaroslav@1890: * possibly block current thread; jaroslav@1890: * } jaroslav@1890: * jaroslav@1890: * Release: jaroslav@1890: * if (tryRelease(arg)) jaroslav@1890: * unblock the first queued thread; jaroslav@1890: *jaroslav@1890: * jaroslav@1890: * (Shared mode is similar but may involve cascading signals.) jaroslav@1890: * jaroslav@1890: *
Because checks in acquire are invoked before
jaroslav@1890: * enqueuing, a newly acquiring thread may barge ahead of
jaroslav@1890: * others that are blocked and queued. However, you can, if desired,
jaroslav@1890: * define tryAcquire and/or tryAcquireShared to
jaroslav@1890: * disable barging by internally invoking one or more of the inspection
jaroslav@1890: * methods, thereby providing a fair FIFO acquisition order.
jaroslav@1890: * In particular, most fair synchronizers can define tryAcquire
jaroslav@1890: * to return false if {@link #hasQueuedPredecessors} (a method
jaroslav@1890: * specifically designed to be used by fair synchronizers) returns
jaroslav@1890: * true. Other variations are possible.
jaroslav@1890: *
jaroslav@1890: * Throughput and scalability are generally highest for the
jaroslav@1890: * default barging (also known as greedy,
jaroslav@1890: * renouncement, and convoy-avoidance) strategy.
jaroslav@1890: * While this is not guaranteed to be fair or starvation-free, earlier
jaroslav@1890: * queued threads are allowed to recontend before later queued
jaroslav@1890: * threads, and each recontention has an unbiased chance to succeed
jaroslav@1890: * against incoming threads. Also, while acquires do not
jaroslav@1890: * "spin" in the usual sense, they may perform multiple
jaroslav@1890: * invocations of tryAcquire interspersed with other
jaroslav@1890: * computations before blocking. This gives most of the benefits of
jaroslav@1890: * spins when exclusive synchronization is only briefly held, without
jaroslav@1890: * most of the liabilities when it isn't. If so desired, you can
jaroslav@1890: * augment this by preceding calls to acquire methods with
jaroslav@1890: * "fast-path" checks, possibly prechecking {@link #hasContended}
jaroslav@1890: * and/or {@link #hasQueuedThreads} to only do so if the synchronizer
jaroslav@1890: * is likely not to be contended.
jaroslav@1890: *
jaroslav@1890: * This class provides an efficient and scalable basis for
jaroslav@1890: * synchronization in part by specializing its range of use to
jaroslav@1890: * synchronizers that can rely on int state, acquire, and
jaroslav@1890: * release parameters, and an internal FIFO wait queue. When this does
jaroslav@1890: * not suffice, you can build synchronizers from a lower level using
jaroslav@1890: * {@link java.util.concurrent.atomic atomic} classes, your own custom
jaroslav@1890: * {@link java.util.Queue} classes, and {@link LockSupport} blocking
jaroslav@1890: * support.
jaroslav@1890: *
jaroslav@1890: * Here is a non-reentrant mutual exclusion lock class that uses
jaroslav@1890: * the value zero to represent the unlocked state, and one to
jaroslav@1890: * represent the locked state. While a non-reentrant lock
jaroslav@1890: * does not strictly require recording of the current owner
jaroslav@1890: * thread, this class does so anyway to make usage easier to monitor.
jaroslav@1890: * It also supports conditions and exposes
jaroslav@1890: * one of the instrumentation methods:
jaroslav@1890: *
jaroslav@1890: * Here is a latch class that is like a {@link CountDownLatch}
jaroslav@1890: * except that it only requires a single signal to
jaroslav@1890: * fire. Because a latch is non-exclusive, it uses the shared
jaroslav@1890: * acquire and release methods.
jaroslav@1890: *
jaroslav@1890: * The wait queue is a variant of a "CLH" (Craig, Landin, and
jaroslav@1890: * Hagersten) lock queue. CLH locks are normally used for
jaroslav@1890: * spinlocks. We instead use them for blocking synchronizers, but
jaroslav@1890: * use the same basic tactic of holding some of the control
jaroslav@1890: * information about a thread in the predecessor of its node. A
jaroslav@1890: * "status" field in each node keeps track of whether a thread
jaroslav@1890: * should block. A node is signalled when its predecessor
jaroslav@1890: * releases. Each node of the queue otherwise serves as a
jaroslav@1890: * specific-notification-style monitor holding a single waiting
jaroslav@1890: * thread. The status field does NOT control whether threads are
jaroslav@1890: * granted locks etc though. A thread may try to acquire if it is
jaroslav@1890: * first in the queue. But being first does not guarantee success;
jaroslav@1890: * it only gives the right to contend. So the currently released
jaroslav@1890: * contender thread may need to rewait.
jaroslav@1890: *
jaroslav@1890: * To enqueue into a CLH lock, you atomically splice it in as new
jaroslav@1890: * tail. To dequeue, you just set the head field.
jaroslav@1890: * Insertion into a CLH queue requires only a single atomic
jaroslav@1890: * operation on "tail", so there is a simple atomic point of
jaroslav@1890: * demarcation from unqueued to queued. Similarly, dequeing
jaroslav@1890: * involves only updating the "head". However, it takes a bit
jaroslav@1890: * more work for nodes to determine who their successors are,
jaroslav@1890: * in part to deal with possible cancellation due to timeouts
jaroslav@1890: * and interrupts.
jaroslav@1890: *
jaroslav@1890: * The "prev" links (not used in original CLH locks), are mainly
jaroslav@1890: * needed to handle cancellation. If a node is cancelled, its
jaroslav@1890: * successor is (normally) relinked to a non-cancelled
jaroslav@1890: * predecessor. For explanation of similar mechanics in the case
jaroslav@1890: * of spin locks, see the papers by Scott and Scherer at
jaroslav@1890: * http://www.cs.rochester.edu/u/scott/synchronization/
jaroslav@1890: *
jaroslav@1890: * We also use "next" links to implement blocking mechanics.
jaroslav@1890: * The thread id for each node is kept in its own node, so a
jaroslav@1890: * predecessor signals the next node to wake up by traversing
jaroslav@1890: * next link to determine which thread it is. Determination of
jaroslav@1890: * successor must avoid races with newly queued nodes to set
jaroslav@1890: * the "next" fields of their predecessors. This is solved
jaroslav@1890: * when necessary by checking backwards from the atomically
jaroslav@1890: * updated "tail" when a node's successor appears to be null.
jaroslav@1890: * (Or, said differently, the next-links are an optimization
jaroslav@1890: * so that we don't usually need a backward scan.)
jaroslav@1890: *
jaroslav@1890: * Cancellation introduces some conservatism to the basic
jaroslav@1890: * algorithms. Since we must poll for cancellation of other
jaroslav@1890: * nodes, we can miss noticing whether a cancelled node is
jaroslav@1890: * ahead or behind us. This is dealt with by always unparking
jaroslav@1890: * successors upon cancellation, allowing them to stabilize on
jaroslav@1890: * a new predecessor, unless we can identify an uncancelled
jaroslav@1890: * predecessor who will carry this responsibility.
jaroslav@1890: *
jaroslav@1890: * CLH queues need a dummy header node to get started. But
jaroslav@1890: * we don't create them on construction, because it would be wasted
jaroslav@1890: * effort if there is never contention. Instead, the node
jaroslav@1890: * is constructed and head and tail pointers are set upon first
jaroslav@1890: * contention.
jaroslav@1890: *
jaroslav@1890: * Threads waiting on Conditions use the same nodes, but
jaroslav@1890: * use an additional link. Conditions only need to link nodes
jaroslav@1890: * in simple (non-concurrent) linked queues because they are
jaroslav@1890: * only accessed when exclusively held. Upon await, a node is
jaroslav@1890: * inserted into a condition queue. Upon signal, the node is
jaroslav@1890: * transferred to the main queue. A special value of status
jaroslav@1890: * field is used to mark which queue a node is on.
jaroslav@1890: *
jaroslav@1890: * Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
jaroslav@1890: * Scherer and Michael Scott, along with members of JSR-166
jaroslav@1890: * expert group, for helpful ideas, discussions, and critiques
jaroslav@1890: * on the design of this class.
jaroslav@1890: */
jaroslav@1890: static final class Node {
jaroslav@1890: /** Marker to indicate a node is waiting in shared mode */
jaroslav@1890: static final Node SHARED = new Node();
jaroslav@1890: /** Marker to indicate a node is waiting in exclusive mode */
jaroslav@1890: static final Node EXCLUSIVE = null;
jaroslav@1890:
jaroslav@1890: /** waitStatus value to indicate thread has cancelled */
jaroslav@1890: static final int CANCELLED = 1;
jaroslav@1890: /** waitStatus value to indicate successor's thread needs unparking */
jaroslav@1890: static final int SIGNAL = -1;
jaroslav@1890: /** waitStatus value to indicate thread is waiting on condition */
jaroslav@1890: static final int CONDITION = -2;
jaroslav@1890: /**
jaroslav@1890: * waitStatus value to indicate the next acquireShared should
jaroslav@1890: * unconditionally propagate
jaroslav@1890: */
jaroslav@1890: static final int PROPAGATE = -3;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Status field, taking on only the values:
jaroslav@1890: * SIGNAL: The successor of this node is (or will soon be)
jaroslav@1890: * blocked (via park), so the current node must
jaroslav@1890: * unpark its successor when it releases or
jaroslav@1890: * cancels. To avoid races, acquire methods must
jaroslav@1890: * first indicate they need a signal,
jaroslav@1890: * then retry the atomic acquire, and then,
jaroslav@1890: * on failure, block.
jaroslav@1890: * CANCELLED: This node is cancelled due to timeout or interrupt.
jaroslav@1890: * Nodes never leave this state. In particular,
jaroslav@1890: * a thread with cancelled node never again blocks.
jaroslav@1890: * CONDITION: This node is currently on a condition queue.
jaroslav@1890: * It will not be used as a sync queue node
jaroslav@1890: * until transferred, at which time the status
jaroslav@1890: * will be set to 0. (Use of this value here has
jaroslav@1890: * nothing to do with the other uses of the
jaroslav@1890: * field, but simplifies mechanics.)
jaroslav@1890: * PROPAGATE: A releaseShared should be propagated to other
jaroslav@1890: * nodes. This is set (for head node only) in
jaroslav@1890: * doReleaseShared to ensure propagation
jaroslav@1890: * continues, even if other operations have
jaroslav@1890: * since intervened.
jaroslav@1890: * 0: None of the above
jaroslav@1890: *
jaroslav@1890: * The values are arranged numerically to simplify use.
jaroslav@1890: * Non-negative values mean that a node doesn't need to
jaroslav@1890: * signal. So, most code doesn't need to check for particular
jaroslav@1890: * values, just for sign.
jaroslav@1890: *
jaroslav@1890: * The field is initialized to 0 for normal sync nodes, and
jaroslav@1890: * CONDITION for condition nodes. It is modified using CAS
jaroslav@1890: * (or when possible, unconditional volatile writes).
jaroslav@1890: */
jaroslav@1890: volatile int waitStatus;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Link to predecessor node that current node/thread relies on
jaroslav@1890: * for checking waitStatus. Assigned during enqueing, and nulled
jaroslav@1890: * out (for sake of GC) only upon dequeuing. Also, upon
jaroslav@1890: * cancellation of a predecessor, we short-circuit while
jaroslav@1890: * finding a non-cancelled one, which will always exist
jaroslav@1890: * because the head node is never cancelled: A node becomes
jaroslav@1890: * head only as a result of successful acquire. A
jaroslav@1890: * cancelled thread never succeeds in acquiring, and a thread only
jaroslav@1890: * cancels itself, not any other node.
jaroslav@1890: */
jaroslav@1890: volatile Node prev;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Link to the successor node that the current node/thread
jaroslav@1890: * unparks upon release. Assigned during enqueuing, adjusted
jaroslav@1890: * when bypassing cancelled predecessors, and nulled out (for
jaroslav@1890: * sake of GC) when dequeued. The enq operation does not
jaroslav@1890: * assign next field of a predecessor until after attachment,
jaroslav@1890: * so seeing a null next field does not necessarily mean that
jaroslav@1890: * node is at end of queue. However, if a next field appears
jaroslav@1890: * to be null, we can scan prev's from the tail to
jaroslav@1890: * double-check. The next field of cancelled nodes is set to
jaroslav@1890: * point to the node itself instead of null, to make life
jaroslav@1890: * easier for isOnSyncQueue.
jaroslav@1890: */
jaroslav@1890: volatile Node next;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * The thread that enqueued this node. Initialized on
jaroslav@1890: * construction and nulled out after use.
jaroslav@1890: */
jaroslav@1890: volatile Thread thread;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Link to next node waiting on condition, or the special
jaroslav@1890: * value SHARED. Because condition queues are accessed only
jaroslav@1890: * when holding in exclusive mode, we just need a simple
jaroslav@1890: * linked queue to hold nodes while they are waiting on
jaroslav@1890: * conditions. They are then transferred to the queue to
jaroslav@1890: * re-acquire. And because conditions can only be exclusive,
jaroslav@1890: * we save a field by using special value to indicate shared
jaroslav@1890: * mode.
jaroslav@1890: */
jaroslav@1890: Node nextWaiter;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns true if node is waiting in shared mode
jaroslav@1890: */
jaroslav@1890: final boolean isShared() {
jaroslav@1890: return nextWaiter == SHARED;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns previous node, or throws NullPointerException if null.
jaroslav@1890: * Use when predecessor cannot be null. The null check could
jaroslav@1890: * be elided, but is present to help the VM.
jaroslav@1890: *
jaroslav@1890: * @return the predecessor of this node
jaroslav@1890: */
jaroslav@1890: final Node predecessor() throws NullPointerException {
jaroslav@1890: Node p = prev;
jaroslav@1890: if (p == null)
jaroslav@1890: throw new NullPointerException();
jaroslav@1890: else
jaroslav@1890: return p;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: Node() { // Used to establish initial head or SHARED marker
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: Node(Thread thread, Node mode) { // Used by addWaiter
jaroslav@1890: this.nextWaiter = mode;
jaroslav@1890: this.thread = thread;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: Node(Thread thread, int waitStatus) { // Used by Condition
jaroslav@1890: this.waitStatus = waitStatus;
jaroslav@1890: this.thread = thread;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Head of the wait queue, lazily initialized. Except for
jaroslav@1890: * initialization, it is modified only via method setHead. Note:
jaroslav@1890: * If head exists, its waitStatus is guaranteed not to be
jaroslav@1890: * CANCELLED.
jaroslav@1890: */
jaroslav@1890: private transient volatile Node head;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Tail of the wait queue, lazily initialized. Modified only via
jaroslav@1890: * method enq to add new wait node.
jaroslav@1890: */
jaroslav@1890: private transient volatile Node tail;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * The synchronization state.
jaroslav@1890: */
jaroslav@1890: private volatile int state;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns the current value of synchronization state.
jaroslav@1890: * This operation has memory semantics of a volatile read.
jaroslav@1890: * @return current state value
jaroslav@1890: */
jaroslav@1890: protected final int getState() {
jaroslav@1890: return state;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Sets the value of synchronization state.
jaroslav@1890: * This operation has memory semantics of a volatile write.
jaroslav@1890: * @param newState the new state value
jaroslav@1890: */
jaroslav@1890: protected final void setState(int newState) {
jaroslav@1890: state = newState;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Atomically sets synchronization state to the given updated
jaroslav@1890: * value if the current state value equals the expected value.
jaroslav@1890: * This operation has memory semantics of a volatile read
jaroslav@1890: * and write.
jaroslav@1890: *
jaroslav@1890: * @param expect the expected value
jaroslav@1890: * @param update the new value
jaroslav@1890: * @return true if successful. False return indicates that the actual
jaroslav@1890: * value was not equal to the expected value.
jaroslav@1890: */
jaroslav@1890: protected final boolean compareAndSetState(int expect, int update) {
jaroslav@1890: // See below for intrinsics setup to support this
jaroslav@1890: return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // Queuing utilities
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * The number of nanoseconds for which it is faster to spin
jaroslav@1890: * rather than to use timed park. A rough estimate suffices
jaroslav@1890: * to improve responsiveness with very short timeouts.
jaroslav@1890: */
jaroslav@1890: static final long spinForTimeoutThreshold = 1000L;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Inserts node into queue, initializing if necessary. See picture above.
jaroslav@1890: * @param node the node to insert
jaroslav@1890: * @return node's predecessor
jaroslav@1890: */
jaroslav@1890: private Node enq(final Node node) {
jaroslav@1890: for (;;) {
jaroslav@1890: Node t = tail;
jaroslav@1890: if (t == null) { // Must initialize
jaroslav@1890: if (compareAndSetHead(new Node()))
jaroslav@1890: tail = head;
jaroslav@1890: } else {
jaroslav@1890: node.prev = t;
jaroslav@1890: if (compareAndSetTail(t, node)) {
jaroslav@1890: t.next = node;
jaroslav@1890: return t;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Creates and enqueues node for current thread and given mode.
jaroslav@1890: *
jaroslav@1890: * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
jaroslav@1890: * @return the new node
jaroslav@1890: */
jaroslav@1890: private Node addWaiter(Node mode) {
jaroslav@1890: Node node = new Node(Thread.currentThread(), mode);
jaroslav@1890: // Try the fast path of enq; backup to full enq on failure
jaroslav@1890: Node pred = tail;
jaroslav@1890: if (pred != null) {
jaroslav@1890: node.prev = pred;
jaroslav@1890: if (compareAndSetTail(pred, node)) {
jaroslav@1890: pred.next = node;
jaroslav@1890: return node;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: enq(node);
jaroslav@1890: return node;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Sets head of queue to be node, thus dequeuing. Called only by
jaroslav@1890: * acquire methods. Also nulls out unused fields for sake of GC
jaroslav@1890: * and to suppress unnecessary signals and traversals.
jaroslav@1890: *
jaroslav@1890: * @param node the node
jaroslav@1890: */
jaroslav@1890: private void setHead(Node node) {
jaroslav@1890: head = node;
jaroslav@1890: node.thread = null;
jaroslav@1890: node.prev = null;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Wakes up node's successor, if one exists.
jaroslav@1890: *
jaroslav@1890: * @param node the node
jaroslav@1890: */
jaroslav@1890: private void unparkSuccessor(Node node) {
jaroslav@1890: /*
jaroslav@1890: * If status is negative (i.e., possibly needing signal) try
jaroslav@1890: * to clear in anticipation of signalling. It is OK if this
jaroslav@1890: * fails or if status is changed by waiting thread.
jaroslav@1890: */
jaroslav@1890: int ws = node.waitStatus;
jaroslav@1890: if (ws < 0)
jaroslav@1890: compareAndSetWaitStatus(node, ws, 0);
jaroslav@1890:
jaroslav@1890: /*
jaroslav@1890: * Thread to unpark is held in successor, which is normally
jaroslav@1890: * just the next node. But if cancelled or apparently null,
jaroslav@1890: * traverse backwards from tail to find the actual
jaroslav@1890: * non-cancelled successor.
jaroslav@1890: */
jaroslav@1890: Node s = node.next;
jaroslav@1890: if (s == null || s.waitStatus > 0) {
jaroslav@1890: s = null;
jaroslav@1890: for (Node t = tail; t != null && t != node; t = t.prev)
jaroslav@1890: if (t.waitStatus <= 0)
jaroslav@1890: s = t;
jaroslav@1890: }
jaroslav@1890: if (s != null)
jaroslav@1890: LockSupport.unpark(s.thread);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Release action for shared mode -- signal successor and ensure
jaroslav@1890: * propagation. (Note: For exclusive mode, release just amounts
jaroslav@1890: * to calling unparkSuccessor of head if it needs signal.)
jaroslav@1890: */
jaroslav@1890: private void doReleaseShared() {
jaroslav@1890: /*
jaroslav@1890: * Ensure that a release propagates, even if there are other
jaroslav@1890: * in-progress acquires/releases. This proceeds in the usual
jaroslav@1890: * way of trying to unparkSuccessor of head if it needs
jaroslav@1890: * signal. But if it does not, status is set to PROPAGATE to
jaroslav@1890: * ensure that upon release, propagation continues.
jaroslav@1890: * Additionally, we must loop in case a new node is added
jaroslav@1890: * while we are doing this. Also, unlike other uses of
jaroslav@1890: * unparkSuccessor, we need to know if CAS to reset status
jaroslav@1890: * fails, if so rechecking.
jaroslav@1890: */
jaroslav@1890: for (;;) {
jaroslav@1890: Node h = head;
jaroslav@1890: if (h != null && h != tail) {
jaroslav@1890: int ws = h.waitStatus;
jaroslav@1890: if (ws == Node.SIGNAL) {
jaroslav@1890: if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
jaroslav@1890: continue; // loop to recheck cases
jaroslav@1890: unparkSuccessor(h);
jaroslav@1890: }
jaroslav@1890: else if (ws == 0 &&
jaroslav@1890: !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
jaroslav@1890: continue; // loop on failed CAS
jaroslav@1890: }
jaroslav@1890: if (h == head) // loop if head changed
jaroslav@1890: break;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Sets head of queue, and checks if successor may be waiting
jaroslav@1890: * in shared mode, if so propagating if either propagate > 0 or
jaroslav@1890: * PROPAGATE status was set.
jaroslav@1890: *
jaroslav@1890: * @param node the node
jaroslav@1890: * @param propagate the return value from a tryAcquireShared
jaroslav@1890: */
jaroslav@1890: private void setHeadAndPropagate(Node node, int propagate) {
jaroslav@1890: Node h = head; // Record old head for check below
jaroslav@1890: setHead(node);
jaroslav@1890: /*
jaroslav@1890: * Try to signal next queued node if:
jaroslav@1890: * Propagation was indicated by caller,
jaroslav@1890: * or was recorded (as h.waitStatus) by a previous operation
jaroslav@1890: * (note: this uses sign-check of waitStatus because
jaroslav@1890: * PROPAGATE status may transition to SIGNAL.)
jaroslav@1890: * and
jaroslav@1890: * The next node is waiting in shared mode,
jaroslav@1890: * or we don't know, because it appears null
jaroslav@1890: *
jaroslav@1890: * The conservatism in both of these checks may cause
jaroslav@1890: * unnecessary wake-ups, but only when there are multiple
jaroslav@1890: * racing acquires/releases, so most need signals now or soon
jaroslav@1890: * anyway.
jaroslav@1890: */
jaroslav@1890: if (propagate > 0 || h == null || h.waitStatus < 0) {
jaroslav@1890: Node s = node.next;
jaroslav@1890: if (s == null || s.isShared())
jaroslav@1890: doReleaseShared();
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // Utilities for various versions of acquire
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Cancels an ongoing attempt to acquire.
jaroslav@1890: *
jaroslav@1890: * @param node the node
jaroslav@1890: */
jaroslav@1890: private void cancelAcquire(Node node) {
jaroslav@1890: // Ignore if node doesn't exist
jaroslav@1890: if (node == null)
jaroslav@1890: return;
jaroslav@1890:
jaroslav@1890: node.thread = null;
jaroslav@1890:
jaroslav@1890: // Skip cancelled predecessors
jaroslav@1890: Node pred = node.prev;
jaroslav@1890: while (pred.waitStatus > 0)
jaroslav@1890: node.prev = pred = pred.prev;
jaroslav@1890:
jaroslav@1890: // predNext is the apparent node to unsplice. CASes below will
jaroslav@1890: // fail if not, in which case, we lost race vs another cancel
jaroslav@1890: // or signal, so no further action is necessary.
jaroslav@1890: Node predNext = pred.next;
jaroslav@1890:
jaroslav@1890: // Can use unconditional write instead of CAS here.
jaroslav@1890: // After this atomic step, other Nodes can skip past us.
jaroslav@1890: // Before, we are free of interference from other threads.
jaroslav@1890: node.waitStatus = Node.CANCELLED;
jaroslav@1890:
jaroslav@1890: // If we are the tail, remove ourselves.
jaroslav@1890: if (node == tail && compareAndSetTail(node, pred)) {
jaroslav@1890: compareAndSetNext(pred, predNext, null);
jaroslav@1890: } else {
jaroslav@1890: // If successor needs signal, try to set pred's next-link
jaroslav@1890: // so it will get one. Otherwise wake it up to propagate.
jaroslav@1890: int ws;
jaroslav@1890: if (pred != head &&
jaroslav@1890: ((ws = pred.waitStatus) == Node.SIGNAL ||
jaroslav@1890: (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
jaroslav@1890: pred.thread != null) {
jaroslav@1890: Node next = node.next;
jaroslav@1890: if (next != null && next.waitStatus <= 0)
jaroslav@1890: compareAndSetNext(pred, predNext, next);
jaroslav@1890: } else {
jaroslav@1890: unparkSuccessor(node);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: node.next = node; // help GC
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Checks and updates status for a node that failed to acquire.
jaroslav@1890: * Returns true if thread should block. This is the main signal
jaroslav@1890: * control in all acquire loops. Requires that pred == node.prev
jaroslav@1890: *
jaroslav@1890: * @param pred node's predecessor holding status
jaroslav@1890: * @param node the node
jaroslav@1890: * @return {@code true} if thread should block
jaroslav@1890: */
jaroslav@1890: private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
jaroslav@1890: int ws = pred.waitStatus;
jaroslav@1890: if (ws == Node.SIGNAL)
jaroslav@1890: /*
jaroslav@1890: * This node has already set status asking a release
jaroslav@1890: * to signal it, so it can safely park.
jaroslav@1890: */
jaroslav@1890: return true;
jaroslav@1890: if (ws > 0) {
jaroslav@1890: /*
jaroslav@1890: * Predecessor was cancelled. Skip over predecessors and
jaroslav@1890: * indicate retry.
jaroslav@1890: */
jaroslav@1890: do {
jaroslav@1890: node.prev = pred = pred.prev;
jaroslav@1890: } while (pred.waitStatus > 0);
jaroslav@1890: pred.next = node;
jaroslav@1890: } else {
jaroslav@1890: /*
jaroslav@1890: * waitStatus must be 0 or PROPAGATE. Indicate that we
jaroslav@1890: * need a signal, but don't park yet. Caller will need to
jaroslav@1890: * retry to make sure it cannot acquire before parking.
jaroslav@1890: */
jaroslav@1890: compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
jaroslav@1890: }
jaroslav@1890: return false;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Convenience method to interrupt current thread.
jaroslav@1890: */
jaroslav@1890: private static void selfInterrupt() {
jaroslav@1890: Thread.currentThread().interrupt();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Convenience method to park and then check if interrupted
jaroslav@1890: *
jaroslav@1890: * @return {@code true} if interrupted
jaroslav@1890: */
jaroslav@1890: private final boolean parkAndCheckInterrupt() {
jaroslav@1890: LockSupport.park(this);
jaroslav@1890: return Thread.interrupted();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /*
jaroslav@1890: * Various flavors of acquire, varying in exclusive/shared and
jaroslav@1890: * control modes. Each is mostly the same, but annoyingly
jaroslav@1890: * different. Only a little bit of factoring is possible due to
jaroslav@1890: * interactions of exception mechanics (including ensuring that we
jaroslav@1890: * cancel if tryAcquire throws exception) and other control, at
jaroslav@1890: * least not without hurting performance too much.
jaroslav@1890: */
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in exclusive uninterruptible mode for thread already in
jaroslav@1890: * queue. Used by condition wait methods as well as acquire.
jaroslav@1890: *
jaroslav@1890: * @param node the node
jaroslav@1890: * @param arg the acquire argument
jaroslav@1890: * @return {@code true} if interrupted while waiting
jaroslav@1890: */
jaroslav@1890: final boolean acquireQueued(final Node node, int arg) {
jaroslav@1890: boolean failed = true;
jaroslav@1890: try {
jaroslav@1890: boolean interrupted = false;
jaroslav@1890: for (;;) {
jaroslav@1890: final Node p = node.predecessor();
jaroslav@1890: if (p == head && tryAcquire(arg)) {
jaroslav@1890: setHead(node);
jaroslav@1890: p.next = null; // help GC
jaroslav@1890: failed = false;
jaroslav@1890: return interrupted;
jaroslav@1890: }
jaroslav@1890: if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890: parkAndCheckInterrupt())
jaroslav@1890: interrupted = true;
jaroslav@1890: }
jaroslav@1890: } finally {
jaroslav@1890: if (failed)
jaroslav@1890: cancelAcquire(node);
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in exclusive interruptible mode.
jaroslav@1890: * @param arg the acquire argument
jaroslav@1890: */
jaroslav@1890: private void doAcquireInterruptibly(int arg)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: final Node node = addWaiter(Node.EXCLUSIVE);
jaroslav@1890: boolean failed = true;
jaroslav@1890: try {
jaroslav@1890: for (;;) {
jaroslav@1890: final Node p = node.predecessor();
jaroslav@1890: if (p == head && tryAcquire(arg)) {
jaroslav@1890: setHead(node);
jaroslav@1890: p.next = null; // help GC
jaroslav@1890: failed = false;
jaroslav@1890: return;
jaroslav@1890: }
jaroslav@1890: if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890: parkAndCheckInterrupt())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: }
jaroslav@1890: } finally {
jaroslav@1890: if (failed)
jaroslav@1890: cancelAcquire(node);
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in exclusive timed mode.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument
jaroslav@1890: * @param nanosTimeout max wait time
jaroslav@1890: * @return {@code true} if acquired
jaroslav@1890: */
jaroslav@1890: private boolean doAcquireNanos(int arg, long nanosTimeout)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: long lastTime = System.nanoTime();
jaroslav@1890: final Node node = addWaiter(Node.EXCLUSIVE);
jaroslav@1890: boolean failed = true;
jaroslav@1890: try {
jaroslav@1890: for (;;) {
jaroslav@1890: final Node p = node.predecessor();
jaroslav@1890: if (p == head && tryAcquire(arg)) {
jaroslav@1890: setHead(node);
jaroslav@1890: p.next = null; // help GC
jaroslav@1890: failed = false;
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: if (nanosTimeout <= 0)
jaroslav@1890: return false;
jaroslav@1890: if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890: nanosTimeout > spinForTimeoutThreshold)
jaroslav@1890: LockSupport.parkNanos(this, nanosTimeout);
jaroslav@1890: long now = System.nanoTime();
jaroslav@1890: nanosTimeout -= now - lastTime;
jaroslav@1890: lastTime = now;
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: }
jaroslav@1890: } finally {
jaroslav@1890: if (failed)
jaroslav@1890: cancelAcquire(node);
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in shared uninterruptible mode.
jaroslav@1890: * @param arg the acquire argument
jaroslav@1890: */
jaroslav@1890: private void doAcquireShared(int arg) {
jaroslav@1890: final Node node = addWaiter(Node.SHARED);
jaroslav@1890: boolean failed = true;
jaroslav@1890: try {
jaroslav@1890: boolean interrupted = false;
jaroslav@1890: for (;;) {
jaroslav@1890: final Node p = node.predecessor();
jaroslav@1890: if (p == head) {
jaroslav@1890: int r = tryAcquireShared(arg);
jaroslav@1890: if (r >= 0) {
jaroslav@1890: setHeadAndPropagate(node, r);
jaroslav@1890: p.next = null; // help GC
jaroslav@1890: if (interrupted)
jaroslav@1890: selfInterrupt();
jaroslav@1890: failed = false;
jaroslav@1890: return;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890: parkAndCheckInterrupt())
jaroslav@1890: interrupted = true;
jaroslav@1890: }
jaroslav@1890: } finally {
jaroslav@1890: if (failed)
jaroslav@1890: cancelAcquire(node);
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in shared interruptible mode.
jaroslav@1890: * @param arg the acquire argument
jaroslav@1890: */
jaroslav@1890: private void doAcquireSharedInterruptibly(int arg)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: final Node node = addWaiter(Node.SHARED);
jaroslav@1890: boolean failed = true;
jaroslav@1890: try {
jaroslav@1890: for (;;) {
jaroslav@1890: final Node p = node.predecessor();
jaroslav@1890: if (p == head) {
jaroslav@1890: int r = tryAcquireShared(arg);
jaroslav@1890: if (r >= 0) {
jaroslav@1890: setHeadAndPropagate(node, r);
jaroslav@1890: p.next = null; // help GC
jaroslav@1890: failed = false;
jaroslav@1890: return;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890: parkAndCheckInterrupt())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: }
jaroslav@1890: } finally {
jaroslav@1890: if (failed)
jaroslav@1890: cancelAcquire(node);
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in shared timed mode.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument
jaroslav@1890: * @param nanosTimeout max wait time
jaroslav@1890: * @return {@code true} if acquired
jaroslav@1890: */
jaroslav@1890: private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
jaroslav@1890: throws InterruptedException {
jaroslav@1890:
jaroslav@1890: long lastTime = System.nanoTime();
jaroslav@1890: final Node node = addWaiter(Node.SHARED);
jaroslav@1890: boolean failed = true;
jaroslav@1890: try {
jaroslav@1890: for (;;) {
jaroslav@1890: final Node p = node.predecessor();
jaroslav@1890: if (p == head) {
jaroslav@1890: int r = tryAcquireShared(arg);
jaroslav@1890: if (r >= 0) {
jaroslav@1890: setHeadAndPropagate(node, r);
jaroslav@1890: p.next = null; // help GC
jaroslav@1890: failed = false;
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890: if (nanosTimeout <= 0)
jaroslav@1890: return false;
jaroslav@1890: if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890: nanosTimeout > spinForTimeoutThreshold)
jaroslav@1890: LockSupport.parkNanos(this, nanosTimeout);
jaroslav@1890: long now = System.nanoTime();
jaroslav@1890: nanosTimeout -= now - lastTime;
jaroslav@1890: lastTime = now;
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: }
jaroslav@1890: } finally {
jaroslav@1890: if (failed)
jaroslav@1890: cancelAcquire(node);
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // Main exported methods
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Attempts to acquire in exclusive mode. This method should query
jaroslav@1890: * if the state of the object permits it to be acquired in the
jaroslav@1890: * exclusive mode, and if so to acquire it.
jaroslav@1890: *
jaroslav@1890: * This method is always invoked by the thread performing
jaroslav@1890: * acquire. If this method reports failure, the acquire method
jaroslav@1890: * may queue the thread, if it is not already queued, until it is
jaroslav@1890: * signalled by a release from some other thread. This can be used
jaroslav@1890: * to implement method {@link Lock#tryLock()}.
jaroslav@1890: *
jaroslav@1890: * The default
jaroslav@1890: * implementation throws {@link UnsupportedOperationException}.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument. This value is always the one
jaroslav@1890: * passed to an acquire method, or is the value saved on entry
jaroslav@1890: * to a condition wait. The value is otherwise uninterpreted
jaroslav@1890: * and can represent anything you like.
jaroslav@1890: * @return {@code true} if successful. Upon success, this object has
jaroslav@1890: * been acquired.
jaroslav@1890: * @throws IllegalMonitorStateException if acquiring would place this
jaroslav@1890: * synchronizer in an illegal state. This exception must be
jaroslav@1890: * thrown in a consistent fashion for synchronization to work
jaroslav@1890: * correctly.
jaroslav@1890: * @throws UnsupportedOperationException if exclusive mode is not supported
jaroslav@1890: */
jaroslav@1890: protected boolean tryAcquire(int arg) {
jaroslav@1890: throw new UnsupportedOperationException();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Attempts to set the state to reflect a release in exclusive
jaroslav@1890: * mode.
jaroslav@1890: *
jaroslav@1890: * This method is always invoked by the thread performing release.
jaroslav@1890: *
jaroslav@1890: * The default implementation throws
jaroslav@1890: * {@link UnsupportedOperationException}.
jaroslav@1890: *
jaroslav@1890: * @param arg the release argument. This value is always the one
jaroslav@1890: * passed to a release method, or the current state value upon
jaroslav@1890: * entry to a condition wait. The value is otherwise
jaroslav@1890: * uninterpreted and can represent anything you like.
jaroslav@1890: * @return {@code true} if this object is now in a fully released
jaroslav@1890: * state, so that any waiting threads may attempt to acquire;
jaroslav@1890: * and {@code false} otherwise.
jaroslav@1890: * @throws IllegalMonitorStateException if releasing would place this
jaroslav@1890: * synchronizer in an illegal state. This exception must be
jaroslav@1890: * thrown in a consistent fashion for synchronization to work
jaroslav@1890: * correctly.
jaroslav@1890: * @throws UnsupportedOperationException if exclusive mode is not supported
jaroslav@1890: */
jaroslav@1890: protected boolean tryRelease(int arg) {
jaroslav@1890: throw new UnsupportedOperationException();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Attempts to acquire in shared mode. This method should query if
jaroslav@1890: * the state of the object permits it to be acquired in the shared
jaroslav@1890: * mode, and if so to acquire it.
jaroslav@1890: *
jaroslav@1890: * This method is always invoked by the thread performing
jaroslav@1890: * acquire. If this method reports failure, the acquire method
jaroslav@1890: * may queue the thread, if it is not already queued, until it is
jaroslav@1890: * signalled by a release from some other thread.
jaroslav@1890: *
jaroslav@1890: * The default implementation throws {@link
jaroslav@1890: * UnsupportedOperationException}.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument. This value is always the one
jaroslav@1890: * passed to an acquire method, or is the value saved on entry
jaroslav@1890: * to a condition wait. The value is otherwise uninterpreted
jaroslav@1890: * and can represent anything you like.
jaroslav@1890: * @return a negative value on failure; zero if acquisition in shared
jaroslav@1890: * mode succeeded but no subsequent shared-mode acquire can
jaroslav@1890: * succeed; and a positive value if acquisition in shared
jaroslav@1890: * mode succeeded and subsequent shared-mode acquires might
jaroslav@1890: * also succeed, in which case a subsequent waiting thread
jaroslav@1890: * must check availability. (Support for three different
jaroslav@1890: * return values enables this method to be used in contexts
jaroslav@1890: * where acquires only sometimes act exclusively.) Upon
jaroslav@1890: * success, this object has been acquired.
jaroslav@1890: * @throws IllegalMonitorStateException if acquiring would place this
jaroslav@1890: * synchronizer in an illegal state. This exception must be
jaroslav@1890: * thrown in a consistent fashion for synchronization to work
jaroslav@1890: * correctly.
jaroslav@1890: * @throws UnsupportedOperationException if shared mode is not supported
jaroslav@1890: */
jaroslav@1890: protected int tryAcquireShared(int arg) {
jaroslav@1890: throw new UnsupportedOperationException();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Attempts to set the state to reflect a release in shared mode.
jaroslav@1890: *
jaroslav@1890: * This method is always invoked by the thread performing release.
jaroslav@1890: *
jaroslav@1890: * The default implementation throws
jaroslav@1890: * {@link UnsupportedOperationException}.
jaroslav@1890: *
jaroslav@1890: * @param arg the release argument. This value is always the one
jaroslav@1890: * passed to a release method, or the current state value upon
jaroslav@1890: * entry to a condition wait. The value is otherwise
jaroslav@1890: * uninterpreted and can represent anything you like.
jaroslav@1890: * @return {@code true} if this release of shared mode may permit a
jaroslav@1890: * waiting acquire (shared or exclusive) to succeed; and
jaroslav@1890: * {@code false} otherwise
jaroslav@1890: * @throws IllegalMonitorStateException if releasing would place this
jaroslav@1890: * synchronizer in an illegal state. This exception must be
jaroslav@1890: * thrown in a consistent fashion for synchronization to work
jaroslav@1890: * correctly.
jaroslav@1890: * @throws UnsupportedOperationException if shared mode is not supported
jaroslav@1890: */
jaroslav@1890: protected boolean tryReleaseShared(int arg) {
jaroslav@1890: throw new UnsupportedOperationException();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns {@code true} if synchronization is held exclusively with
jaroslav@1890: * respect to the current (calling) thread. This method is invoked
jaroslav@1890: * upon each call to a non-waiting {@link ConditionObject} method.
jaroslav@1890: * (Waiting methods instead invoke {@link #release}.)
jaroslav@1890: *
jaroslav@1890: * The default implementation throws {@link
jaroslav@1890: * UnsupportedOperationException}. This method is invoked
jaroslav@1890: * internally only within {@link ConditionObject} methods, so need
jaroslav@1890: * not be defined if conditions are not used.
jaroslav@1890: *
jaroslav@1890: * @return {@code true} if synchronization is held exclusively;
jaroslav@1890: * {@code false} otherwise
jaroslav@1890: * @throws UnsupportedOperationException if conditions are not supported
jaroslav@1890: */
jaroslav@1890: protected boolean isHeldExclusively() {
jaroslav@1890: throw new UnsupportedOperationException();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in exclusive mode, ignoring interrupts. Implemented
jaroslav@1890: * by invoking at least once {@link #tryAcquire},
jaroslav@1890: * returning on success. Otherwise the thread is queued, possibly
jaroslav@1890: * repeatedly blocking and unblocking, invoking {@link
jaroslav@1890: * #tryAcquire} until success. This method can be used
jaroslav@1890: * to implement method {@link Lock#lock}.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument. This value is conveyed to
jaroslav@1890: * {@link #tryAcquire} but is otherwise uninterpreted and
jaroslav@1890: * can represent anything you like.
jaroslav@1890: */
jaroslav@1890: public final void acquire(int arg) {
jaroslav@1890: if (!tryAcquire(arg) &&
jaroslav@1890: acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
jaroslav@1890: selfInterrupt();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in exclusive mode, aborting if interrupted.
jaroslav@1890: * Implemented by first checking interrupt status, then invoking
jaroslav@1890: * at least once {@link #tryAcquire}, returning on
jaroslav@1890: * success. Otherwise the thread is queued, possibly repeatedly
jaroslav@1890: * blocking and unblocking, invoking {@link #tryAcquire}
jaroslav@1890: * until success or the thread is interrupted. This method can be
jaroslav@1890: * used to implement method {@link Lock#lockInterruptibly}.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument. This value is conveyed to
jaroslav@1890: * {@link #tryAcquire} but is otherwise uninterpreted and
jaroslav@1890: * can represent anything you like.
jaroslav@1890: * @throws InterruptedException if the current thread is interrupted
jaroslav@1890: */
jaroslav@1890: public final void acquireInterruptibly(int arg)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: if (!tryAcquire(arg))
jaroslav@1890: doAcquireInterruptibly(arg);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Attempts to acquire in exclusive mode, aborting if interrupted,
jaroslav@1890: * and failing if the given timeout elapses. Implemented by first
jaroslav@1890: * checking interrupt status, then invoking at least once {@link
jaroslav@1890: * #tryAcquire}, returning on success. Otherwise, the thread is
jaroslav@1890: * queued, possibly repeatedly blocking and unblocking, invoking
jaroslav@1890: * {@link #tryAcquire} until success or the thread is interrupted
jaroslav@1890: * or the timeout elapses. This method can be used to implement
jaroslav@1890: * method {@link Lock#tryLock(long, TimeUnit)}.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument. This value is conveyed to
jaroslav@1890: * {@link #tryAcquire} but is otherwise uninterpreted and
jaroslav@1890: * can represent anything you like.
jaroslav@1890: * @param nanosTimeout the maximum number of nanoseconds to wait
jaroslav@1890: * @return {@code true} if acquired; {@code false} if timed out
jaroslav@1890: * @throws InterruptedException if the current thread is interrupted
jaroslav@1890: */
jaroslav@1890: public final boolean tryAcquireNanos(int arg, long nanosTimeout)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: return tryAcquire(arg) ||
jaroslav@1890: doAcquireNanos(arg, nanosTimeout);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Releases in exclusive mode. Implemented by unblocking one or
jaroslav@1890: * more threads if {@link #tryRelease} returns true.
jaroslav@1890: * This method can be used to implement method {@link Lock#unlock}.
jaroslav@1890: *
jaroslav@1890: * @param arg the release argument. This value is conveyed to
jaroslav@1890: * {@link #tryRelease} but is otherwise uninterpreted and
jaroslav@1890: * can represent anything you like.
jaroslav@1890: * @return the value returned from {@link #tryRelease}
jaroslav@1890: */
jaroslav@1890: public final boolean release(int arg) {
jaroslav@1890: if (tryRelease(arg)) {
jaroslav@1890: Node h = head;
jaroslav@1890: if (h != null && h.waitStatus != 0)
jaroslav@1890: unparkSuccessor(h);
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: return false;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in shared mode, ignoring interrupts. Implemented by
jaroslav@1890: * first invoking at least once {@link #tryAcquireShared},
jaroslav@1890: * returning on success. Otherwise the thread is queued, possibly
jaroslav@1890: * repeatedly blocking and unblocking, invoking {@link
jaroslav@1890: * #tryAcquireShared} until success.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument. This value is conveyed to
jaroslav@1890: * {@link #tryAcquireShared} but is otherwise uninterpreted
jaroslav@1890: * and can represent anything you like.
jaroslav@1890: */
jaroslav@1890: public final void acquireShared(int arg) {
jaroslav@1890: if (tryAcquireShared(arg) < 0)
jaroslav@1890: doAcquireShared(arg);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Acquires in shared mode, aborting if interrupted. Implemented
jaroslav@1890: * by first checking interrupt status, then invoking at least once
jaroslav@1890: * {@link #tryAcquireShared}, returning on success. Otherwise the
jaroslav@1890: * thread is queued, possibly repeatedly blocking and unblocking,
jaroslav@1890: * invoking {@link #tryAcquireShared} until success or the thread
jaroslav@1890: * is interrupted.
jaroslav@1890: * @param arg the acquire argument
jaroslav@1890: * This value is conveyed to {@link #tryAcquireShared} but is
jaroslav@1890: * otherwise uninterpreted and can represent anything
jaroslav@1890: * you like.
jaroslav@1890: * @throws InterruptedException if the current thread is interrupted
jaroslav@1890: */
jaroslav@1890: public final void acquireSharedInterruptibly(int arg)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: if (tryAcquireShared(arg) < 0)
jaroslav@1890: doAcquireSharedInterruptibly(arg);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Attempts to acquire in shared mode, aborting if interrupted, and
jaroslav@1890: * failing if the given timeout elapses. Implemented by first
jaroslav@1890: * checking interrupt status, then invoking at least once {@link
jaroslav@1890: * #tryAcquireShared}, returning on success. Otherwise, the
jaroslav@1890: * thread is queued, possibly repeatedly blocking and unblocking,
jaroslav@1890: * invoking {@link #tryAcquireShared} until success or the thread
jaroslav@1890: * is interrupted or the timeout elapses.
jaroslav@1890: *
jaroslav@1890: * @param arg the acquire argument. This value is conveyed to
jaroslav@1890: * {@link #tryAcquireShared} but is otherwise uninterpreted
jaroslav@1890: * and can represent anything you like.
jaroslav@1890: * @param nanosTimeout the maximum number of nanoseconds to wait
jaroslav@1890: * @return {@code true} if acquired; {@code false} if timed out
jaroslav@1890: * @throws InterruptedException if the current thread is interrupted
jaroslav@1890: */
jaroslav@1890: public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: return tryAcquireShared(arg) >= 0 ||
jaroslav@1890: doAcquireSharedNanos(arg, nanosTimeout);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Releases in shared mode. Implemented by unblocking one or more
jaroslav@1890: * threads if {@link #tryReleaseShared} returns true.
jaroslav@1890: *
jaroslav@1890: * @param arg the release argument. This value is conveyed to
jaroslav@1890: * {@link #tryReleaseShared} but is otherwise uninterpreted
jaroslav@1890: * and can represent anything you like.
jaroslav@1890: * @return the value returned from {@link #tryReleaseShared}
jaroslav@1890: */
jaroslav@1890: public final boolean releaseShared(int arg) {
jaroslav@1890: if (tryReleaseShared(arg)) {
jaroslav@1890: doReleaseShared();
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: return false;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // Queue inspection methods
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Queries whether any threads are waiting to acquire. Note that
jaroslav@1890: * because cancellations due to interrupts and timeouts may occur
jaroslav@1890: * at any time, a {@code true} return does not guarantee that any
jaroslav@1890: * other thread will ever acquire.
jaroslav@1890: *
jaroslav@1890: * In this implementation, this operation returns in
jaroslav@1890: * constant time.
jaroslav@1890: *
jaroslav@1890: * @return {@code true} if there may be other threads waiting to acquire
jaroslav@1890: */
jaroslav@1890: public final boolean hasQueuedThreads() {
jaroslav@1890: return head != tail;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Queries whether any threads have ever contended to acquire this
jaroslav@1890: * synchronizer; that is if an acquire method has ever blocked.
jaroslav@1890: *
jaroslav@1890: * In this implementation, this operation returns in
jaroslav@1890: * constant time.
jaroslav@1890: *
jaroslav@1890: * @return {@code true} if there has ever been contention
jaroslav@1890: */
jaroslav@1890: public final boolean hasContended() {
jaroslav@1890: return head != null;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns the first (longest-waiting) thread in the queue, or
jaroslav@1890: * {@code null} if no threads are currently queued.
jaroslav@1890: *
jaroslav@1890: * In this implementation, this operation normally returns in
jaroslav@1890: * constant time, but may iterate upon contention if other threads are
jaroslav@1890: * concurrently modifying the queue.
jaroslav@1890: *
jaroslav@1890: * @return the first (longest-waiting) thread in the queue, or
jaroslav@1890: * {@code null} if no threads are currently queued
jaroslav@1890: */
jaroslav@1890: public final Thread getFirstQueuedThread() {
jaroslav@1890: // handle only fast path, else relay
jaroslav@1890: return (head == tail) ? null : fullGetFirstQueuedThread();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Version of getFirstQueuedThread called when fastpath fails
jaroslav@1890: */
jaroslav@1890: private Thread fullGetFirstQueuedThread() {
jaroslav@1890: /*
jaroslav@1890: * The first node is normally head.next. Try to get its
jaroslav@1890: * thread field, ensuring consistent reads: If thread
jaroslav@1890: * field is nulled out or s.prev is no longer head, then
jaroslav@1890: * some other thread(s) concurrently performed setHead in
jaroslav@1890: * between some of our reads. We try this twice before
jaroslav@1890: * resorting to traversal.
jaroslav@1890: */
jaroslav@1890: Node h, s;
jaroslav@1890: Thread st;
jaroslav@1890: if (((h = head) != null && (s = h.next) != null &&
jaroslav@1890: s.prev == head && (st = s.thread) != null) ||
jaroslav@1890: ((h = head) != null && (s = h.next) != null &&
jaroslav@1890: s.prev == head && (st = s.thread) != null))
jaroslav@1890: return st;
jaroslav@1890:
jaroslav@1890: /*
jaroslav@1890: * Head's next field might not have been set yet, or may have
jaroslav@1890: * been unset after setHead. So we must check to see if tail
jaroslav@1890: * is actually first node. If not, we continue on, safely
jaroslav@1890: * traversing from tail back to head to find first,
jaroslav@1890: * guaranteeing termination.
jaroslav@1890: */
jaroslav@1890:
jaroslav@1890: Node t = tail;
jaroslav@1890: Thread firstThread = null;
jaroslav@1890: while (t != null && t != head) {
jaroslav@1890: Thread tt = t.thread;
jaroslav@1890: if (tt != null)
jaroslav@1890: firstThread = tt;
jaroslav@1890: t = t.prev;
jaroslav@1890: }
jaroslav@1890: return firstThread;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns true if the given thread is currently queued.
jaroslav@1890: *
jaroslav@1890: * This implementation traverses the queue to determine
jaroslav@1890: * presence of the given thread.
jaroslav@1890: *
jaroslav@1890: * @param thread the thread
jaroslav@1890: * @return {@code true} if the given thread is on the queue
jaroslav@1890: * @throws NullPointerException if the thread is null
jaroslav@1890: */
jaroslav@1890: public final boolean isQueued(Thread thread) {
jaroslav@1890: if (thread == null)
jaroslav@1890: throw new NullPointerException();
jaroslav@1890: for (Node p = tail; p != null; p = p.prev)
jaroslav@1890: if (p.thread == thread)
jaroslav@1890: return true;
jaroslav@1890: return false;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns {@code true} if the apparent first queued thread, if one
jaroslav@1890: * exists, is waiting in exclusive mode. If this method returns
jaroslav@1890: * {@code true}, and the current thread is attempting to acquire in
jaroslav@1890: * shared mode (that is, this method is invoked from {@link
jaroslav@1890: * #tryAcquireShared}) then it is guaranteed that the current thread
jaroslav@1890: * is not the first queued thread. Used only as a heuristic in
jaroslav@1890: * ReentrantReadWriteLock.
jaroslav@1890: */
jaroslav@1890: final boolean apparentlyFirstQueuedIsExclusive() {
jaroslav@1890: Node h, s;
jaroslav@1890: return (h = head) != null &&
jaroslav@1890: (s = h.next) != null &&
jaroslav@1890: !s.isShared() &&
jaroslav@1890: s.thread != null;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Queries whether any threads have been waiting to acquire longer
jaroslav@1890: * than the current thread.
jaroslav@1890: *
jaroslav@1890: * An invocation of this method is equivalent to (but may be
jaroslav@1890: * more efficient than):
jaroslav@1890: * Note that because cancellations due to interrupts and
jaroslav@1890: * timeouts may occur at any time, a {@code true} return does not
jaroslav@1890: * guarantee that some other thread will acquire before the current
jaroslav@1890: * thread. Likewise, it is possible for another thread to win a
jaroslav@1890: * race to enqueue after this method has returned {@code false},
jaroslav@1890: * due to the queue being empty.
jaroslav@1890: *
jaroslav@1890: * This method is designed to be used by a fair synchronizer to
jaroslav@1890: * avoid barging.
jaroslav@1890: * Such a synchronizer's {@link #tryAcquire} method should return
jaroslav@1890: * {@code false}, and its {@link #tryAcquireShared} method should
jaroslav@1890: * return a negative value, if this method returns {@code true}
jaroslav@1890: * (unless this is a reentrant acquire). For example, the {@code
jaroslav@1890: * tryAcquire} method for a fair, reentrant, exclusive mode
jaroslav@1890: * synchronizer might look like this:
jaroslav@1890: *
jaroslav@1890: * Method documentation for this class describes mechanics,
jaroslav@1890: * not behavioral specifications from the point of view of Lock
jaroslav@1890: * and Condition users. Exported versions of this class will in
jaroslav@1890: * general need to be accompanied by documentation describing
jaroslav@1890: * condition semantics that rely on those of the associated
jaroslav@1890: * AbstractQueuedSynchronizer.
jaroslav@1890: *
jaroslav@1890: * This class is Serializable, but all fields are transient,
jaroslav@1890: * so deserialized conditions have no waiters.
jaroslav@1890: */
jaroslav@1890: public class ConditionObject implements Condition, java.io.Serializable {
jaroslav@1890: private static final long serialVersionUID = 1173984872572414699L;
jaroslav@1890: /** First node of condition queue. */
jaroslav@1890: private transient Node firstWaiter;
jaroslav@1890: /** Last node of condition queue. */
jaroslav@1890: private transient Node lastWaiter;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Creates a new ConditionObject instance.
jaroslav@1890: */
jaroslav@1890: public ConditionObject() { }
jaroslav@1890:
jaroslav@1890: // Internal methods
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Adds a new waiter to wait queue.
jaroslav@1890: * @return its new wait node
jaroslav@1890: */
jaroslav@1890: private Node addConditionWaiter() {
jaroslav@1890: Node t = lastWaiter;
jaroslav@1890: // If lastWaiter is cancelled, clean out.
jaroslav@1890: if (t != null && t.waitStatus != Node.CONDITION) {
jaroslav@1890: unlinkCancelledWaiters();
jaroslav@1890: t = lastWaiter;
jaroslav@1890: }
jaroslav@1890: Node node = new Node(Thread.currentThread(), Node.CONDITION);
jaroslav@1890: if (t == null)
jaroslav@1890: firstWaiter = node;
jaroslav@1890: else
jaroslav@1890: t.nextWaiter = node;
jaroslav@1890: lastWaiter = node;
jaroslav@1890: return node;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Removes and transfers nodes until hit non-cancelled one or
jaroslav@1890: * null. Split out from signal in part to encourage compilers
jaroslav@1890: * to inline the case of no waiters.
jaroslav@1890: * @param first (non-null) the first node on condition queue
jaroslav@1890: */
jaroslav@1890: private void doSignal(Node first) {
jaroslav@1890: do {
jaroslav@1890: if ( (firstWaiter = first.nextWaiter) == null)
jaroslav@1890: lastWaiter = null;
jaroslav@1890: first.nextWaiter = null;
jaroslav@1890: } while (!transferForSignal(first) &&
jaroslav@1890: (first = firstWaiter) != null);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Removes and transfers all nodes.
jaroslav@1890: * @param first (non-null) the first node on condition queue
jaroslav@1890: */
jaroslav@1890: private void doSignalAll(Node first) {
jaroslav@1890: lastWaiter = firstWaiter = null;
jaroslav@1890: do {
jaroslav@1890: Node next = first.nextWaiter;
jaroslav@1890: first.nextWaiter = null;
jaroslav@1890: transferForSignal(first);
jaroslav@1890: first = next;
jaroslav@1890: } while (first != null);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Unlinks cancelled waiter nodes from condition queue.
jaroslav@1890: * Called only while holding lock. This is called when
jaroslav@1890: * cancellation occurred during condition wait, and upon
jaroslav@1890: * insertion of a new waiter when lastWaiter is seen to have
jaroslav@1890: * been cancelled. This method is needed to avoid garbage
jaroslav@1890: * retention in the absence of signals. So even though it may
jaroslav@1890: * require a full traversal, it comes into play only when
jaroslav@1890: * timeouts or cancellations occur in the absence of
jaroslav@1890: * signals. It traverses all nodes rather than stopping at a
jaroslav@1890: * particular target to unlink all pointers to garbage nodes
jaroslav@1890: * without requiring many re-traversals during cancellation
jaroslav@1890: * storms.
jaroslav@1890: */
jaroslav@1890: private void unlinkCancelledWaiters() {
jaroslav@1890: Node t = firstWaiter;
jaroslav@1890: Node trail = null;
jaroslav@1890: while (t != null) {
jaroslav@1890: Node next = t.nextWaiter;
jaroslav@1890: if (t.waitStatus != Node.CONDITION) {
jaroslav@1890: t.nextWaiter = null;
jaroslav@1890: if (trail == null)
jaroslav@1890: firstWaiter = next;
jaroslav@1890: else
jaroslav@1890: trail.nextWaiter = next;
jaroslav@1890: if (next == null)
jaroslav@1890: lastWaiter = trail;
jaroslav@1890: }
jaroslav@1890: else
jaroslav@1890: trail = t;
jaroslav@1890: t = next;
jaroslav@1890: }
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // public methods
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Moves the longest-waiting thread, if one exists, from the
jaroslav@1890: * wait queue for this condition to the wait queue for the
jaroslav@1890: * owning lock.
jaroslav@1890: *
jaroslav@1890: * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890: * returns {@code false}
jaroslav@1890: */
jaroslav@1890: public final void signal() {
jaroslav@1890: if (!isHeldExclusively())
jaroslav@1890: throw new IllegalMonitorStateException();
jaroslav@1890: Node first = firstWaiter;
jaroslav@1890: if (first != null)
jaroslav@1890: doSignal(first);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Moves all threads from the wait queue for this condition to
jaroslav@1890: * the wait queue for the owning lock.
jaroslav@1890: *
jaroslav@1890: * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890: * returns {@code false}
jaroslav@1890: */
jaroslav@1890: public final void signalAll() {
jaroslav@1890: if (!isHeldExclusively())
jaroslav@1890: throw new IllegalMonitorStateException();
jaroslav@1890: Node first = firstWaiter;
jaroslav@1890: if (first != null)
jaroslav@1890: doSignalAll(first);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Implements uninterruptible condition wait.
jaroslav@1890: * Usage Examples
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: * class Mutex implements Lock, java.io.Serializable {
jaroslav@1890: *
jaroslav@1890: * // Our internal helper class
jaroslav@1890: * private static class Sync extends AbstractQueuedSynchronizer {
jaroslav@1890: * // Report whether in locked state
jaroslav@1890: * protected boolean isHeldExclusively() {
jaroslav@1890: * return getState() == 1;
jaroslav@1890: * }
jaroslav@1890: *
jaroslav@1890: * // Acquire the lock if state is zero
jaroslav@1890: * public boolean tryAcquire(int acquires) {
jaroslav@1890: * assert acquires == 1; // Otherwise unused
jaroslav@1890: * if (compareAndSetState(0, 1)) {
jaroslav@1890: * setExclusiveOwnerThread(Thread.currentThread());
jaroslav@1890: * return true;
jaroslav@1890: * }
jaroslav@1890: * return false;
jaroslav@1890: * }
jaroslav@1890: *
jaroslav@1890: * // Release the lock by setting state to zero
jaroslav@1890: * protected boolean tryRelease(int releases) {
jaroslav@1890: * assert releases == 1; // Otherwise unused
jaroslav@1890: * if (getState() == 0) throw new IllegalMonitorStateException();
jaroslav@1890: * setExclusiveOwnerThread(null);
jaroslav@1890: * setState(0);
jaroslav@1890: * return true;
jaroslav@1890: * }
jaroslav@1890: *
jaroslav@1890: * // Provide a Condition
jaroslav@1890: * Condition newCondition() { return new ConditionObject(); }
jaroslav@1890: *
jaroslav@1890: * // Deserialize properly
jaroslav@1890: * private void readObject(ObjectInputStream s)
jaroslav@1890: * throws IOException, ClassNotFoundException {
jaroslav@1890: * s.defaultReadObject();
jaroslav@1890: * setState(0); // reset to unlocked state
jaroslav@1890: * }
jaroslav@1890: * }
jaroslav@1890: *
jaroslav@1890: * // The sync object does all the hard work. We just forward to it.
jaroslav@1890: * private final Sync sync = new Sync();
jaroslav@1890: *
jaroslav@1890: * public void lock() { sync.acquire(1); }
jaroslav@1890: * public boolean tryLock() { return sync.tryAcquire(1); }
jaroslav@1890: * public void unlock() { sync.release(1); }
jaroslav@1890: * public Condition newCondition() { return sync.newCondition(); }
jaroslav@1890: * public boolean isLocked() { return sync.isHeldExclusively(); }
jaroslav@1890: * public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
jaroslav@1890: * public void lockInterruptibly() throws InterruptedException {
jaroslav@1890: * sync.acquireInterruptibly(1);
jaroslav@1890: * }
jaroslav@1890: * public boolean tryLock(long timeout, TimeUnit unit)
jaroslav@1890: * throws InterruptedException {
jaroslav@1890: * return sync.tryAcquireNanos(1, unit.toNanos(timeout));
jaroslav@1890: * }
jaroslav@1890: * }
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: * class BooleanLatch {
jaroslav@1890: *
jaroslav@1890: * private static class Sync extends AbstractQueuedSynchronizer {
jaroslav@1890: * boolean isSignalled() { return getState() != 0; }
jaroslav@1890: *
jaroslav@1890: * protected int tryAcquireShared(int ignore) {
jaroslav@1890: * return isSignalled() ? 1 : -1;
jaroslav@1890: * }
jaroslav@1890: *
jaroslav@1890: * protected boolean tryReleaseShared(int ignore) {
jaroslav@1890: * setState(1);
jaroslav@1890: * return true;
jaroslav@1890: * }
jaroslav@1890: * }
jaroslav@1890: *
jaroslav@1890: * private final Sync sync = new Sync();
jaroslav@1890: * public boolean isSignalled() { return sync.isSignalled(); }
jaroslav@1890: * public void signal() { sync.releaseShared(1); }
jaroslav@1890: * public void await() throws InterruptedException {
jaroslav@1890: * sync.acquireSharedInterruptibly(1);
jaroslav@1890: * }
jaroslav@1890: * }
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: * @since 1.5
jaroslav@1890: * @author Doug Lea
jaroslav@1890: */
jaroslav@1890: public abstract class AbstractQueuedSynchronizer
jaroslav@1890: extends AbstractOwnableSynchronizer
jaroslav@1890: implements java.io.Serializable {
jaroslav@1890:
jaroslav@1890: private static final long serialVersionUID = 7373984972572414691L;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Creates a new AbstractQueuedSynchronizer instance
jaroslav@1890: * with initial synchronization state of zero.
jaroslav@1890: */
jaroslav@1890: protected AbstractQueuedSynchronizer() { }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Wait queue node class.
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: * +------+ prev +-----+ +-----+
jaroslav@1890: * head | | <---- | | <---- | | tail
jaroslav@1890: * +------+ +-----+ +-----+
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: * {@code
jaroslav@1890: * getFirstQueuedThread() != Thread.currentThread() &&
jaroslav@1890: * hasQueuedThreads()}
jaroslav@1890: *
jaroslav@1890: * {@code
jaroslav@1890: * protected boolean tryAcquire(int arg) {
jaroslav@1890: * if (isHeldExclusively()) {
jaroslav@1890: * // A reentrant acquire; increment hold count
jaroslav@1890: * return true;
jaroslav@1890: * } else if (hasQueuedPredecessors()) {
jaroslav@1890: * return false;
jaroslav@1890: * } else {
jaroslav@1890: * // try to acquire normally
jaroslav@1890: * }
jaroslav@1890: * }}
jaroslav@1890: *
jaroslav@1890: * @return {@code true} if there is a queued thread preceding the
jaroslav@1890: * current thread, and {@code false} if the current thread
jaroslav@1890: * is at the head of the queue or the queue is empty
jaroslav@1890: * @since 1.7
jaroslav@1890: */
jaroslav@1890: public final boolean hasQueuedPredecessors() {
jaroslav@1890: // The correctness of this depends on head being initialized
jaroslav@1890: // before tail and on head.next being accurate if the current
jaroslav@1890: // thread is first in queue.
jaroslav@1890: Node t = tail; // Read fields in reverse initialization order
jaroslav@1890: Node h = head;
jaroslav@1890: Node s;
jaroslav@1890: return h != t &&
jaroslav@1890: ((s = h.next) == null || s.thread != Thread.currentThread());
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890:
jaroslav@1890: // Instrumentation and monitoring methods
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns an estimate of the number of threads waiting to
jaroslav@1890: * acquire. The value is only an estimate because the number of
jaroslav@1890: * threads may change dynamically while this method traverses
jaroslav@1890: * internal data structures. This method is designed for use in
jaroslav@1890: * monitoring system state, not for synchronization
jaroslav@1890: * control.
jaroslav@1890: *
jaroslav@1890: * @return the estimated number of threads waiting to acquire
jaroslav@1890: */
jaroslav@1890: public final int getQueueLength() {
jaroslav@1890: int n = 0;
jaroslav@1890: for (Node p = tail; p != null; p = p.prev) {
jaroslav@1890: if (p.thread != null)
jaroslav@1890: ++n;
jaroslav@1890: }
jaroslav@1890: return n;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns a collection containing threads that may be waiting to
jaroslav@1890: * acquire. Because the actual set of threads may change
jaroslav@1890: * dynamically while constructing this result, the returned
jaroslav@1890: * collection is only a best-effort estimate. The elements of the
jaroslav@1890: * returned collection are in no particular order. This method is
jaroslav@1890: * designed to facilitate construction of subclasses that provide
jaroslav@1890: * more extensive monitoring facilities.
jaroslav@1890: *
jaroslav@1890: * @return the collection of threads
jaroslav@1890: */
jaroslav@1890: public final Collection
jaroslav@1890: *
jaroslav@1890: */
jaroslav@1890: public final void awaitUninterruptibly() {
jaroslav@1890: Node node = addConditionWaiter();
jaroslav@1890: int savedState = fullyRelease(node);
jaroslav@1890: boolean interrupted = false;
jaroslav@1890: while (!isOnSyncQueue(node)) {
jaroslav@1890: LockSupport.park(this);
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: interrupted = true;
jaroslav@1890: }
jaroslav@1890: if (acquireQueued(node, savedState) || interrupted)
jaroslav@1890: selfInterrupt();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /*
jaroslav@1890: * For interruptible waits, we need to track whether to throw
jaroslav@1890: * InterruptedException, if interrupted while blocked on
jaroslav@1890: * condition, versus reinterrupt current thread, if
jaroslav@1890: * interrupted while blocked waiting to re-acquire.
jaroslav@1890: */
jaroslav@1890:
jaroslav@1890: /** Mode meaning to reinterrupt on exit from wait */
jaroslav@1890: private static final int REINTERRUPT = 1;
jaroslav@1890: /** Mode meaning to throw InterruptedException on exit from wait */
jaroslav@1890: private static final int THROW_IE = -1;
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Checks for interrupt, returning THROW_IE if interrupted
jaroslav@1890: * before signalled, REINTERRUPT if after signalled, or
jaroslav@1890: * 0 if not interrupted.
jaroslav@1890: */
jaroslav@1890: private int checkInterruptWhileWaiting(Node node) {
jaroslav@1890: return Thread.interrupted() ?
jaroslav@1890: (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
jaroslav@1890: 0;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Throws InterruptedException, reinterrupts current thread, or
jaroslav@1890: * does nothing, depending on mode.
jaroslav@1890: */
jaroslav@1890: private void reportInterruptAfterWait(int interruptMode)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: if (interruptMode == THROW_IE)
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: else if (interruptMode == REINTERRUPT)
jaroslav@1890: selfInterrupt();
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Implements interruptible condition wait.
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: */
jaroslav@1890: public final void await() throws InterruptedException {
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: Node node = addConditionWaiter();
jaroslav@1890: int savedState = fullyRelease(node);
jaroslav@1890: int interruptMode = 0;
jaroslav@1890: while (!isOnSyncQueue(node)) {
jaroslav@1890: LockSupport.park(this);
jaroslav@1890: if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
jaroslav@1890: break;
jaroslav@1890: }
jaroslav@1890: if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
jaroslav@1890: interruptMode = REINTERRUPT;
jaroslav@1890: if (node.nextWaiter != null) // clean up if cancelled
jaroslav@1890: unlinkCancelledWaiters();
jaroslav@1890: if (interruptMode != 0)
jaroslav@1890: reportInterruptAfterWait(interruptMode);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Implements timed condition wait.
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: */
jaroslav@1890: public final long awaitNanos(long nanosTimeout)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: Node node = addConditionWaiter();
jaroslav@1890: int savedState = fullyRelease(node);
jaroslav@1890: long lastTime = System.nanoTime();
jaroslav@1890: int interruptMode = 0;
jaroslav@1890: while (!isOnSyncQueue(node)) {
jaroslav@1890: if (nanosTimeout <= 0L) {
jaroslav@1890: transferAfterCancelledWait(node);
jaroslav@1890: break;
jaroslav@1890: }
jaroslav@1890: LockSupport.parkNanos(this, nanosTimeout);
jaroslav@1890: if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
jaroslav@1890: break;
jaroslav@1890:
jaroslav@1890: long now = System.nanoTime();
jaroslav@1890: nanosTimeout -= now - lastTime;
jaroslav@1890: lastTime = now;
jaroslav@1890: }
jaroslav@1890: if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
jaroslav@1890: interruptMode = REINTERRUPT;
jaroslav@1890: if (node.nextWaiter != null)
jaroslav@1890: unlinkCancelledWaiters();
jaroslav@1890: if (interruptMode != 0)
jaroslav@1890: reportInterruptAfterWait(interruptMode);
jaroslav@1890: return nanosTimeout - (System.nanoTime() - lastTime);
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Implements absolute timed condition wait.
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: */
jaroslav@1890: public final boolean awaitUntil(Date deadline)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: if (deadline == null)
jaroslav@1890: throw new NullPointerException();
jaroslav@1890: long abstime = deadline.getTime();
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: Node node = addConditionWaiter();
jaroslav@1890: int savedState = fullyRelease(node);
jaroslav@1890: boolean timedout = false;
jaroslav@1890: int interruptMode = 0;
jaroslav@1890: while (!isOnSyncQueue(node)) {
jaroslav@1890: if (System.currentTimeMillis() > abstime) {
jaroslav@1890: timedout = transferAfterCancelledWait(node);
jaroslav@1890: break;
jaroslav@1890: }
jaroslav@1890: LockSupport.parkUntil(this, abstime);
jaroslav@1890: if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
jaroslav@1890: break;
jaroslav@1890: }
jaroslav@1890: if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
jaroslav@1890: interruptMode = REINTERRUPT;
jaroslav@1890: if (node.nextWaiter != null)
jaroslav@1890: unlinkCancelledWaiters();
jaroslav@1890: if (interruptMode != 0)
jaroslav@1890: reportInterruptAfterWait(interruptMode);
jaroslav@1890: return !timedout;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Implements timed condition wait.
jaroslav@1890: *
jaroslav@1890: *
jaroslav@1890: */
jaroslav@1890: public final boolean await(long time, TimeUnit unit)
jaroslav@1890: throws InterruptedException {
jaroslav@1890: if (unit == null)
jaroslav@1890: throw new NullPointerException();
jaroslav@1890: long nanosTimeout = unit.toNanos(time);
jaroslav@1890: if (Thread.interrupted())
jaroslav@1890: throw new InterruptedException();
jaroslav@1890: Node node = addConditionWaiter();
jaroslav@1890: int savedState = fullyRelease(node);
jaroslav@1890: long lastTime = System.nanoTime();
jaroslav@1890: boolean timedout = false;
jaroslav@1890: int interruptMode = 0;
jaroslav@1890: while (!isOnSyncQueue(node)) {
jaroslav@1890: if (nanosTimeout <= 0L) {
jaroslav@1890: timedout = transferAfterCancelledWait(node);
jaroslav@1890: break;
jaroslav@1890: }
jaroslav@1890: if (nanosTimeout >= spinForTimeoutThreshold)
jaroslav@1890: LockSupport.parkNanos(this, nanosTimeout);
jaroslav@1890: if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
jaroslav@1890: break;
jaroslav@1890: long now = System.nanoTime();
jaroslav@1890: nanosTimeout -= now - lastTime;
jaroslav@1890: lastTime = now;
jaroslav@1890: }
jaroslav@1890: if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
jaroslav@1890: interruptMode = REINTERRUPT;
jaroslav@1890: if (node.nextWaiter != null)
jaroslav@1890: unlinkCancelledWaiters();
jaroslav@1890: if (interruptMode != 0)
jaroslav@1890: reportInterruptAfterWait(interruptMode);
jaroslav@1890: return !timedout;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: // support for instrumentation
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns true if this condition was created by the given
jaroslav@1890: * synchronization object.
jaroslav@1890: *
jaroslav@1890: * @return {@code true} if owned
jaroslav@1890: */
jaroslav@1890: final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
jaroslav@1890: return sync == AbstractQueuedSynchronizer.this;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Queries whether any threads are waiting on this condition.
jaroslav@1890: * Implements {@link AbstractQueuedSynchronizer#hasWaiters}.
jaroslav@1890: *
jaroslav@1890: * @return {@code true} if there are any waiting threads
jaroslav@1890: * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890: * returns {@code false}
jaroslav@1890: */
jaroslav@1890: protected final boolean hasWaiters() {
jaroslav@1890: if (!isHeldExclusively())
jaroslav@1890: throw new IllegalMonitorStateException();
jaroslav@1890: for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
jaroslav@1890: if (w.waitStatus == Node.CONDITION)
jaroslav@1890: return true;
jaroslav@1890: }
jaroslav@1890: return false;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns an estimate of the number of threads waiting on
jaroslav@1890: * this condition.
jaroslav@1890: * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}.
jaroslav@1890: *
jaroslav@1890: * @return the estimated number of waiting threads
jaroslav@1890: * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890: * returns {@code false}
jaroslav@1890: */
jaroslav@1890: protected final int getWaitQueueLength() {
jaroslav@1890: if (!isHeldExclusively())
jaroslav@1890: throw new IllegalMonitorStateException();
jaroslav@1890: int n = 0;
jaroslav@1890: for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
jaroslav@1890: if (w.waitStatus == Node.CONDITION)
jaroslav@1890: ++n;
jaroslav@1890: }
jaroslav@1890: return n;
jaroslav@1890: }
jaroslav@1890:
jaroslav@1890: /**
jaroslav@1890: * Returns a collection containing those threads that may be
jaroslav@1890: * waiting on this Condition.
jaroslav@1890: * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}.
jaroslav@1890: *
jaroslav@1890: * @return the collection of threads
jaroslav@1890: * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890: * returns {@code false}
jaroslav@1890: */
jaroslav@1890: protected final Collection