rt/emul/compact/src/main/java/java/util/concurrent/locks/AbstractQueuedSynchronizer.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 11:01:40 +0100
changeset 1894 75ee4eca04e3
parent 1890 212417b74b72
permissions -rw-r--r--
Can compile java.util.concurrent.locks
jaroslav@1890
     1
/*
jaroslav@1890
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
jaroslav@1890
     3
 *
jaroslav@1890
     4
 * This code is free software; you can redistribute it and/or modify it
jaroslav@1890
     5
 * under the terms of the GNU General Public License version 2 only, as
jaroslav@1890
     6
 * published by the Free Software Foundation.  Oracle designates this
jaroslav@1890
     7
 * particular file as subject to the "Classpath" exception as provided
jaroslav@1890
     8
 * by Oracle in the LICENSE file that accompanied this code.
jaroslav@1890
     9
 *
jaroslav@1890
    10
 * This code is distributed in the hope that it will be useful, but WITHOUT
jaroslav@1890
    11
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
jaroslav@1890
    12
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
jaroslav@1890
    13
 * version 2 for more details (a copy is included in the LICENSE file that
jaroslav@1890
    14
 * accompanied this code).
jaroslav@1890
    15
 *
jaroslav@1890
    16
 * You should have received a copy of the GNU General Public License version
jaroslav@1890
    17
 * 2 along with this work; if not, write to the Free Software Foundation,
jaroslav@1890
    18
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
jaroslav@1890
    19
 *
jaroslav@1890
    20
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
jaroslav@1890
    21
 * or visit www.oracle.com if you need additional information or have any
jaroslav@1890
    22
 * questions.
jaroslav@1890
    23
 */
jaroslav@1890
    24
jaroslav@1890
    25
/*
jaroslav@1890
    26
 * This file is available under and governed by the GNU General Public
jaroslav@1890
    27
 * License version 2 only, as published by the Free Software Foundation.
jaroslav@1890
    28
 * However, the following notice accompanied the original version of this
jaroslav@1890
    29
 * file:
jaroslav@1890
    30
 *
jaroslav@1890
    31
 * Written by Doug Lea with assistance from members of JCP JSR-166
jaroslav@1890
    32
 * Expert Group and released to the public domain, as explained at
jaroslav@1890
    33
 * http://creativecommons.org/publicdomain/zero/1.0/
jaroslav@1890
    34
 */
jaroslav@1890
    35
jaroslav@1890
    36
package java.util.concurrent.locks;
jaroslav@1890
    37
import java.util.*;
jaroslav@1890
    38
import java.util.concurrent.*;
jaroslav@1890
    39
jaroslav@1890
    40
/**
jaroslav@1890
    41
 * Provides a framework for implementing blocking locks and related
jaroslav@1890
    42
 * synchronizers (semaphores, events, etc) that rely on
jaroslav@1890
    43
 * first-in-first-out (FIFO) wait queues.  This class is designed to
jaroslav@1890
    44
 * be a useful basis for most kinds of synchronizers that rely on a
jaroslav@1890
    45
 * single atomic <tt>int</tt> value to represent state. Subclasses
jaroslav@1890
    46
 * must define the protected methods that change this state, and which
jaroslav@1890
    47
 * define what that state means in terms of this object being acquired
jaroslav@1890
    48
 * or released.  Given these, the other methods in this class carry
jaroslav@1890
    49
 * out all queuing and blocking mechanics. Subclasses can maintain
jaroslav@1890
    50
 * other state fields, but only the atomically updated <tt>int</tt>
jaroslav@1890
    51
 * value manipulated using methods {@link #getState}, {@link
jaroslav@1890
    52
 * #setState} and {@link #compareAndSetState} is tracked with respect
jaroslav@1890
    53
 * to synchronization.
jaroslav@1890
    54
 *
jaroslav@1890
    55
 * <p>Subclasses should be defined as non-public internal helper
jaroslav@1890
    56
 * classes that are used to implement the synchronization properties
jaroslav@1890
    57
 * of their enclosing class.  Class
jaroslav@1890
    58
 * <tt>AbstractQueuedSynchronizer</tt> does not implement any
jaroslav@1890
    59
 * synchronization interface.  Instead it defines methods such as
jaroslav@1890
    60
 * {@link #acquireInterruptibly} that can be invoked as
jaroslav@1890
    61
 * appropriate by concrete locks and related synchronizers to
jaroslav@1890
    62
 * implement their public methods.
jaroslav@1890
    63
 *
jaroslav@1890
    64
 * <p>This class supports either or both a default <em>exclusive</em>
jaroslav@1890
    65
 * mode and a <em>shared</em> mode. When acquired in exclusive mode,
jaroslav@1890
    66
 * attempted acquires by other threads cannot succeed. Shared mode
jaroslav@1890
    67
 * acquires by multiple threads may (but need not) succeed. This class
jaroslav@1890
    68
 * does not &quot;understand&quot; these differences except in the
jaroslav@1890
    69
 * mechanical sense that when a shared mode acquire succeeds, the next
jaroslav@1890
    70
 * waiting thread (if one exists) must also determine whether it can
jaroslav@1890
    71
 * acquire as well. Threads waiting in the different modes share the
jaroslav@1890
    72
 * same FIFO queue. Usually, implementation subclasses support only
jaroslav@1890
    73
 * one of these modes, but both can come into play for example in a
jaroslav@1890
    74
 * {@link ReadWriteLock}. Subclasses that support only exclusive or
jaroslav@1890
    75
 * only shared modes need not define the methods supporting the unused mode.
jaroslav@1890
    76
 *
jaroslav@1890
    77
 * <p>This class defines a nested {@link ConditionObject} class that
jaroslav@1890
    78
 * can be used as a {@link Condition} implementation by subclasses
jaroslav@1890
    79
 * supporting exclusive mode for which method {@link
jaroslav@1890
    80
 * #isHeldExclusively} reports whether synchronization is exclusively
jaroslav@1890
    81
 * held with respect to the current thread, method {@link #release}
jaroslav@1890
    82
 * invoked with the current {@link #getState} value fully releases
jaroslav@1890
    83
 * this object, and {@link #acquire}, given this saved state value,
jaroslav@1890
    84
 * eventually restores this object to its previous acquired state.  No
jaroslav@1890
    85
 * <tt>AbstractQueuedSynchronizer</tt> method otherwise creates such a
jaroslav@1890
    86
 * condition, so if this constraint cannot be met, do not use it.  The
jaroslav@1890
    87
 * behavior of {@link ConditionObject} depends of course on the
jaroslav@1890
    88
 * semantics of its synchronizer implementation.
jaroslav@1890
    89
 *
jaroslav@1890
    90
 * <p>This class provides inspection, instrumentation, and monitoring
jaroslav@1890
    91
 * methods for the internal queue, as well as similar methods for
jaroslav@1890
    92
 * condition objects. These can be exported as desired into classes
jaroslav@1890
    93
 * using an <tt>AbstractQueuedSynchronizer</tt> for their
jaroslav@1890
    94
 * synchronization mechanics.
jaroslav@1890
    95
 *
jaroslav@1890
    96
 * <p>Serialization of this class stores only the underlying atomic
jaroslav@1890
    97
 * integer maintaining state, so deserialized objects have empty
jaroslav@1890
    98
 * thread queues. Typical subclasses requiring serializability will
jaroslav@1890
    99
 * define a <tt>readObject</tt> method that restores this to a known
jaroslav@1890
   100
 * initial state upon deserialization.
jaroslav@1890
   101
 *
jaroslav@1890
   102
 * <h3>Usage</h3>
jaroslav@1890
   103
 *
jaroslav@1890
   104
 * <p>To use this class as the basis of a synchronizer, redefine the
jaroslav@1890
   105
 * following methods, as applicable, by inspecting and/or modifying
jaroslav@1890
   106
 * the synchronization state using {@link #getState}, {@link
jaroslav@1890
   107
 * #setState} and/or {@link #compareAndSetState}:
jaroslav@1890
   108
 *
jaroslav@1890
   109
 * <ul>
jaroslav@1890
   110
 * <li> {@link #tryAcquire}
jaroslav@1890
   111
 * <li> {@link #tryRelease}
jaroslav@1890
   112
 * <li> {@link #tryAcquireShared}
jaroslav@1890
   113
 * <li> {@link #tryReleaseShared}
jaroslav@1890
   114
 * <li> {@link #isHeldExclusively}
jaroslav@1890
   115
 *</ul>
jaroslav@1890
   116
 *
jaroslav@1890
   117
 * Each of these methods by default throws {@link
jaroslav@1890
   118
 * UnsupportedOperationException}.  Implementations of these methods
jaroslav@1890
   119
 * must be internally thread-safe, and should in general be short and
jaroslav@1890
   120
 * not block. Defining these methods is the <em>only</em> supported
jaroslav@1890
   121
 * means of using this class. All other methods are declared
jaroslav@1890
   122
 * <tt>final</tt> because they cannot be independently varied.
jaroslav@1890
   123
 *
jaroslav@1890
   124
 * <p>You may also find the inherited methods from {@link
jaroslav@1890
   125
 * AbstractOwnableSynchronizer} useful to keep track of the thread
jaroslav@1890
   126
 * owning an exclusive synchronizer.  You are encouraged to use them
jaroslav@1890
   127
 * -- this enables monitoring and diagnostic tools to assist users in
jaroslav@1890
   128
 * determining which threads hold locks.
jaroslav@1890
   129
 *
jaroslav@1890
   130
 * <p>Even though this class is based on an internal FIFO queue, it
jaroslav@1890
   131
 * does not automatically enforce FIFO acquisition policies.  The core
jaroslav@1890
   132
 * of exclusive synchronization takes the form:
jaroslav@1890
   133
 *
jaroslav@1890
   134
 * <pre>
jaroslav@1890
   135
 * Acquire:
jaroslav@1890
   136
 *     while (!tryAcquire(arg)) {
jaroslav@1890
   137
 *        <em>enqueue thread if it is not already queued</em>;
jaroslav@1890
   138
 *        <em>possibly block current thread</em>;
jaroslav@1890
   139
 *     }
jaroslav@1890
   140
 *
jaroslav@1890
   141
 * Release:
jaroslav@1890
   142
 *     if (tryRelease(arg))
jaroslav@1890
   143
 *        <em>unblock the first queued thread</em>;
jaroslav@1890
   144
 * </pre>
jaroslav@1890
   145
 *
jaroslav@1890
   146
 * (Shared mode is similar but may involve cascading signals.)
jaroslav@1890
   147
 *
jaroslav@1890
   148
 * <p><a name="barging">Because checks in acquire are invoked before
jaroslav@1890
   149
 * enqueuing, a newly acquiring thread may <em>barge</em> ahead of
jaroslav@1890
   150
 * others that are blocked and queued.  However, you can, if desired,
jaroslav@1890
   151
 * define <tt>tryAcquire</tt> and/or <tt>tryAcquireShared</tt> to
jaroslav@1890
   152
 * disable barging by internally invoking one or more of the inspection
jaroslav@1890
   153
 * methods, thereby providing a <em>fair</em> FIFO acquisition order.
jaroslav@1890
   154
 * In particular, most fair synchronizers can define <tt>tryAcquire</tt>
jaroslav@1890
   155
 * to return <tt>false</tt> if {@link #hasQueuedPredecessors} (a method
jaroslav@1890
   156
 * specifically designed to be used by fair synchronizers) returns
jaroslav@1890
   157
 * <tt>true</tt>.  Other variations are possible.
jaroslav@1890
   158
 *
jaroslav@1890
   159
 * <p>Throughput and scalability are generally highest for the
jaroslav@1890
   160
 * default barging (also known as <em>greedy</em>,
jaroslav@1890
   161
 * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
jaroslav@1890
   162
 * While this is not guaranteed to be fair or starvation-free, earlier
jaroslav@1890
   163
 * queued threads are allowed to recontend before later queued
jaroslav@1890
   164
 * threads, and each recontention has an unbiased chance to succeed
jaroslav@1890
   165
 * against incoming threads.  Also, while acquires do not
jaroslav@1890
   166
 * &quot;spin&quot; in the usual sense, they may perform multiple
jaroslav@1890
   167
 * invocations of <tt>tryAcquire</tt> interspersed with other
jaroslav@1890
   168
 * computations before blocking.  This gives most of the benefits of
jaroslav@1890
   169
 * spins when exclusive synchronization is only briefly held, without
jaroslav@1890
   170
 * most of the liabilities when it isn't. If so desired, you can
jaroslav@1890
   171
 * augment this by preceding calls to acquire methods with
jaroslav@1890
   172
 * "fast-path" checks, possibly prechecking {@link #hasContended}
jaroslav@1890
   173
 * and/or {@link #hasQueuedThreads} to only do so if the synchronizer
jaroslav@1890
   174
 * is likely not to be contended.
jaroslav@1890
   175
 *
jaroslav@1890
   176
 * <p>This class provides an efficient and scalable basis for
jaroslav@1890
   177
 * synchronization in part by specializing its range of use to
jaroslav@1890
   178
 * synchronizers that can rely on <tt>int</tt> state, acquire, and
jaroslav@1890
   179
 * release parameters, and an internal FIFO wait queue. When this does
jaroslav@1890
   180
 * not suffice, you can build synchronizers from a lower level using
jaroslav@1890
   181
 * {@link java.util.concurrent.atomic atomic} classes, your own custom
jaroslav@1890
   182
 * {@link java.util.Queue} classes, and {@link LockSupport} blocking
jaroslav@1890
   183
 * support.
jaroslav@1890
   184
 *
jaroslav@1890
   185
 * <h3>Usage Examples</h3>
jaroslav@1890
   186
 *
jaroslav@1890
   187
 * <p>Here is a non-reentrant mutual exclusion lock class that uses
jaroslav@1890
   188
 * the value zero to represent the unlocked state, and one to
jaroslav@1890
   189
 * represent the locked state. While a non-reentrant lock
jaroslav@1890
   190
 * does not strictly require recording of the current owner
jaroslav@1890
   191
 * thread, this class does so anyway to make usage easier to monitor.
jaroslav@1890
   192
 * It also supports conditions and exposes
jaroslav@1890
   193
 * one of the instrumentation methods:
jaroslav@1890
   194
 *
jaroslav@1890
   195
 * <pre>
jaroslav@1890
   196
 * class Mutex implements Lock, java.io.Serializable {
jaroslav@1890
   197
 *
jaroslav@1890
   198
 *   // Our internal helper class
jaroslav@1890
   199
 *   private static class Sync extends AbstractQueuedSynchronizer {
jaroslav@1890
   200
 *     // Report whether in locked state
jaroslav@1890
   201
 *     protected boolean isHeldExclusively() {
jaroslav@1890
   202
 *       return getState() == 1;
jaroslav@1890
   203
 *     }
jaroslav@1890
   204
 *
jaroslav@1890
   205
 *     // Acquire the lock if state is zero
jaroslav@1890
   206
 *     public boolean tryAcquire(int acquires) {
jaroslav@1890
   207
 *       assert acquires == 1; // Otherwise unused
jaroslav@1890
   208
 *       if (compareAndSetState(0, 1)) {
jaroslav@1890
   209
 *         setExclusiveOwnerThread(Thread.currentThread());
jaroslav@1890
   210
 *         return true;
jaroslav@1890
   211
 *       }
jaroslav@1890
   212
 *       return false;
jaroslav@1890
   213
 *     }
jaroslav@1890
   214
 *
jaroslav@1890
   215
 *     // Release the lock by setting state to zero
jaroslav@1890
   216
 *     protected boolean tryRelease(int releases) {
jaroslav@1890
   217
 *       assert releases == 1; // Otherwise unused
jaroslav@1890
   218
 *       if (getState() == 0) throw new IllegalMonitorStateException();
jaroslav@1890
   219
 *       setExclusiveOwnerThread(null);
jaroslav@1890
   220
 *       setState(0);
jaroslav@1890
   221
 *       return true;
jaroslav@1890
   222
 *     }
jaroslav@1890
   223
 *
jaroslav@1890
   224
 *     // Provide a Condition
jaroslav@1890
   225
 *     Condition newCondition() { return new ConditionObject(); }
jaroslav@1890
   226
 *
jaroslav@1890
   227
 *     // Deserialize properly
jaroslav@1890
   228
 *     private void readObject(ObjectInputStream s)
jaroslav@1890
   229
 *         throws IOException, ClassNotFoundException {
jaroslav@1890
   230
 *       s.defaultReadObject();
jaroslav@1890
   231
 *       setState(0); // reset to unlocked state
jaroslav@1890
   232
 *     }
jaroslav@1890
   233
 *   }
jaroslav@1890
   234
 *
jaroslav@1890
   235
 *   // The sync object does all the hard work. We just forward to it.
jaroslav@1890
   236
 *   private final Sync sync = new Sync();
jaroslav@1890
   237
 *
jaroslav@1890
   238
 *   public void lock()                { sync.acquire(1); }
jaroslav@1890
   239
 *   public boolean tryLock()          { return sync.tryAcquire(1); }
jaroslav@1890
   240
 *   public void unlock()              { sync.release(1); }
jaroslav@1890
   241
 *   public Condition newCondition()   { return sync.newCondition(); }
jaroslav@1890
   242
 *   public boolean isLocked()         { return sync.isHeldExclusively(); }
jaroslav@1890
   243
 *   public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
jaroslav@1890
   244
 *   public void lockInterruptibly() throws InterruptedException {
jaroslav@1890
   245
 *     sync.acquireInterruptibly(1);
jaroslav@1890
   246
 *   }
jaroslav@1890
   247
 *   public boolean tryLock(long timeout, TimeUnit unit)
jaroslav@1890
   248
 *       throws InterruptedException {
jaroslav@1890
   249
 *     return sync.tryAcquireNanos(1, unit.toNanos(timeout));
jaroslav@1890
   250
 *   }
jaroslav@1890
   251
 * }
jaroslav@1890
   252
 * </pre>
jaroslav@1890
   253
 *
jaroslav@1890
   254
 * <p>Here is a latch class that is like a {@link CountDownLatch}
jaroslav@1890
   255
 * except that it only requires a single <tt>signal</tt> to
jaroslav@1890
   256
 * fire. Because a latch is non-exclusive, it uses the <tt>shared</tt>
jaroslav@1890
   257
 * acquire and release methods.
jaroslav@1890
   258
 *
jaroslav@1890
   259
 * <pre>
jaroslav@1890
   260
 * class BooleanLatch {
jaroslav@1890
   261
 *
jaroslav@1890
   262
 *   private static class Sync extends AbstractQueuedSynchronizer {
jaroslav@1890
   263
 *     boolean isSignalled() { return getState() != 0; }
jaroslav@1890
   264
 *
jaroslav@1890
   265
 *     protected int tryAcquireShared(int ignore) {
jaroslav@1890
   266
 *       return isSignalled() ? 1 : -1;
jaroslav@1890
   267
 *     }
jaroslav@1890
   268
 *
jaroslav@1890
   269
 *     protected boolean tryReleaseShared(int ignore) {
jaroslav@1890
   270
 *       setState(1);
jaroslav@1890
   271
 *       return true;
jaroslav@1890
   272
 *     }
jaroslav@1890
   273
 *   }
jaroslav@1890
   274
 *
jaroslav@1890
   275
 *   private final Sync sync = new Sync();
jaroslav@1890
   276
 *   public boolean isSignalled() { return sync.isSignalled(); }
jaroslav@1890
   277
 *   public void signal()         { sync.releaseShared(1); }
jaroslav@1890
   278
 *   public void await() throws InterruptedException {
jaroslav@1890
   279
 *     sync.acquireSharedInterruptibly(1);
jaroslav@1890
   280
 *   }
jaroslav@1890
   281
 * }
jaroslav@1890
   282
 * </pre>
jaroslav@1890
   283
 *
jaroslav@1890
   284
 * @since 1.5
jaroslav@1890
   285
 * @author Doug Lea
jaroslav@1890
   286
 */
jaroslav@1890
   287
public abstract class AbstractQueuedSynchronizer
jaroslav@1890
   288
    extends AbstractOwnableSynchronizer
jaroslav@1890
   289
    implements java.io.Serializable {
jaroslav@1890
   290
jaroslav@1890
   291
    private static final long serialVersionUID = 7373984972572414691L;
jaroslav@1890
   292
jaroslav@1890
   293
    /**
jaroslav@1890
   294
     * Creates a new <tt>AbstractQueuedSynchronizer</tt> instance
jaroslav@1890
   295
     * with initial synchronization state of zero.
jaroslav@1890
   296
     */
jaroslav@1890
   297
    protected AbstractQueuedSynchronizer() { }
jaroslav@1890
   298
jaroslav@1890
   299
    /**
jaroslav@1890
   300
     * Wait queue node class.
jaroslav@1890
   301
     *
jaroslav@1890
   302
     * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and
jaroslav@1890
   303
     * Hagersten) lock queue. CLH locks are normally used for
jaroslav@1890
   304
     * spinlocks.  We instead use them for blocking synchronizers, but
jaroslav@1890
   305
     * use the same basic tactic of holding some of the control
jaroslav@1890
   306
     * information about a thread in the predecessor of its node.  A
jaroslav@1890
   307
     * "status" field in each node keeps track of whether a thread
jaroslav@1890
   308
     * should block.  A node is signalled when its predecessor
jaroslav@1890
   309
     * releases.  Each node of the queue otherwise serves as a
jaroslav@1890
   310
     * specific-notification-style monitor holding a single waiting
jaroslav@1890
   311
     * thread. The status field does NOT control whether threads are
jaroslav@1890
   312
     * granted locks etc though.  A thread may try to acquire if it is
jaroslav@1890
   313
     * first in the queue. But being first does not guarantee success;
jaroslav@1890
   314
     * it only gives the right to contend.  So the currently released
jaroslav@1890
   315
     * contender thread may need to rewait.
jaroslav@1890
   316
     *
jaroslav@1890
   317
     * <p>To enqueue into a CLH lock, you atomically splice it in as new
jaroslav@1890
   318
     * tail. To dequeue, you just set the head field.
jaroslav@1890
   319
     * <pre>
jaroslav@1890
   320
     *      +------+  prev +-----+       +-----+
jaroslav@1890
   321
     * head |      | <---- |     | <---- |     |  tail
jaroslav@1890
   322
     *      +------+       +-----+       +-----+
jaroslav@1890
   323
     * </pre>
jaroslav@1890
   324
     *
jaroslav@1890
   325
     * <p>Insertion into a CLH queue requires only a single atomic
jaroslav@1890
   326
     * operation on "tail", so there is a simple atomic point of
jaroslav@1890
   327
     * demarcation from unqueued to queued. Similarly, dequeing
jaroslav@1890
   328
     * involves only updating the "head". However, it takes a bit
jaroslav@1890
   329
     * more work for nodes to determine who their successors are,
jaroslav@1890
   330
     * in part to deal with possible cancellation due to timeouts
jaroslav@1890
   331
     * and interrupts.
jaroslav@1890
   332
     *
jaroslav@1890
   333
     * <p>The "prev" links (not used in original CLH locks), are mainly
jaroslav@1890
   334
     * needed to handle cancellation. If a node is cancelled, its
jaroslav@1890
   335
     * successor is (normally) relinked to a non-cancelled
jaroslav@1890
   336
     * predecessor. For explanation of similar mechanics in the case
jaroslav@1890
   337
     * of spin locks, see the papers by Scott and Scherer at
jaroslav@1890
   338
     * http://www.cs.rochester.edu/u/scott/synchronization/
jaroslav@1890
   339
     *
jaroslav@1890
   340
     * <p>We also use "next" links to implement blocking mechanics.
jaroslav@1890
   341
     * The thread id for each node is kept in its own node, so a
jaroslav@1890
   342
     * predecessor signals the next node to wake up by traversing
jaroslav@1890
   343
     * next link to determine which thread it is.  Determination of
jaroslav@1890
   344
     * successor must avoid races with newly queued nodes to set
jaroslav@1890
   345
     * the "next" fields of their predecessors.  This is solved
jaroslav@1890
   346
     * when necessary by checking backwards from the atomically
jaroslav@1890
   347
     * updated "tail" when a node's successor appears to be null.
jaroslav@1890
   348
     * (Or, said differently, the next-links are an optimization
jaroslav@1890
   349
     * so that we don't usually need a backward scan.)
jaroslav@1890
   350
     *
jaroslav@1890
   351
     * <p>Cancellation introduces some conservatism to the basic
jaroslav@1890
   352
     * algorithms.  Since we must poll for cancellation of other
jaroslav@1890
   353
     * nodes, we can miss noticing whether a cancelled node is
jaroslav@1890
   354
     * ahead or behind us. This is dealt with by always unparking
jaroslav@1890
   355
     * successors upon cancellation, allowing them to stabilize on
jaroslav@1890
   356
     * a new predecessor, unless we can identify an uncancelled
jaroslav@1890
   357
     * predecessor who will carry this responsibility.
jaroslav@1890
   358
     *
jaroslav@1890
   359
     * <p>CLH queues need a dummy header node to get started. But
jaroslav@1890
   360
     * we don't create them on construction, because it would be wasted
jaroslav@1890
   361
     * effort if there is never contention. Instead, the node
jaroslav@1890
   362
     * is constructed and head and tail pointers are set upon first
jaroslav@1890
   363
     * contention.
jaroslav@1890
   364
     *
jaroslav@1890
   365
     * <p>Threads waiting on Conditions use the same nodes, but
jaroslav@1890
   366
     * use an additional link. Conditions only need to link nodes
jaroslav@1890
   367
     * in simple (non-concurrent) linked queues because they are
jaroslav@1890
   368
     * only accessed when exclusively held.  Upon await, a node is
jaroslav@1890
   369
     * inserted into a condition queue.  Upon signal, the node is
jaroslav@1890
   370
     * transferred to the main queue.  A special value of status
jaroslav@1890
   371
     * field is used to mark which queue a node is on.
jaroslav@1890
   372
     *
jaroslav@1890
   373
     * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
jaroslav@1890
   374
     * Scherer and Michael Scott, along with members of JSR-166
jaroslav@1890
   375
     * expert group, for helpful ideas, discussions, and critiques
jaroslav@1890
   376
     * on the design of this class.
jaroslav@1890
   377
     */
jaroslav@1890
   378
    static final class Node {
jaroslav@1890
   379
        /** Marker to indicate a node is waiting in shared mode */
jaroslav@1890
   380
        static final Node SHARED = new Node();
jaroslav@1890
   381
        /** Marker to indicate a node is waiting in exclusive mode */
jaroslav@1890
   382
        static final Node EXCLUSIVE = null;
jaroslav@1890
   383
jaroslav@1890
   384
        /** waitStatus value to indicate thread has cancelled */
jaroslav@1890
   385
        static final int CANCELLED =  1;
jaroslav@1890
   386
        /** waitStatus value to indicate successor's thread needs unparking */
jaroslav@1890
   387
        static final int SIGNAL    = -1;
jaroslav@1890
   388
        /** waitStatus value to indicate thread is waiting on condition */
jaroslav@1890
   389
        static final int CONDITION = -2;
jaroslav@1890
   390
        /**
jaroslav@1890
   391
         * waitStatus value to indicate the next acquireShared should
jaroslav@1890
   392
         * unconditionally propagate
jaroslav@1890
   393
         */
jaroslav@1890
   394
        static final int PROPAGATE = -3;
jaroslav@1890
   395
jaroslav@1890
   396
        /**
jaroslav@1890
   397
         * Status field, taking on only the values:
jaroslav@1890
   398
         *   SIGNAL:     The successor of this node is (or will soon be)
jaroslav@1890
   399
         *               blocked (via park), so the current node must
jaroslav@1890
   400
         *               unpark its successor when it releases or
jaroslav@1890
   401
         *               cancels. To avoid races, acquire methods must
jaroslav@1890
   402
         *               first indicate they need a signal,
jaroslav@1890
   403
         *               then retry the atomic acquire, and then,
jaroslav@1890
   404
         *               on failure, block.
jaroslav@1890
   405
         *   CANCELLED:  This node is cancelled due to timeout or interrupt.
jaroslav@1890
   406
         *               Nodes never leave this state. In particular,
jaroslav@1890
   407
         *               a thread with cancelled node never again blocks.
jaroslav@1890
   408
         *   CONDITION:  This node is currently on a condition queue.
jaroslav@1890
   409
         *               It will not be used as a sync queue node
jaroslav@1890
   410
         *               until transferred, at which time the status
jaroslav@1890
   411
         *               will be set to 0. (Use of this value here has
jaroslav@1890
   412
         *               nothing to do with the other uses of the
jaroslav@1890
   413
         *               field, but simplifies mechanics.)
jaroslav@1890
   414
         *   PROPAGATE:  A releaseShared should be propagated to other
jaroslav@1890
   415
         *               nodes. This is set (for head node only) in
jaroslav@1890
   416
         *               doReleaseShared to ensure propagation
jaroslav@1890
   417
         *               continues, even if other operations have
jaroslav@1890
   418
         *               since intervened.
jaroslav@1890
   419
         *   0:          None of the above
jaroslav@1890
   420
         *
jaroslav@1890
   421
         * The values are arranged numerically to simplify use.
jaroslav@1890
   422
         * Non-negative values mean that a node doesn't need to
jaroslav@1890
   423
         * signal. So, most code doesn't need to check for particular
jaroslav@1890
   424
         * values, just for sign.
jaroslav@1890
   425
         *
jaroslav@1890
   426
         * The field is initialized to 0 for normal sync nodes, and
jaroslav@1890
   427
         * CONDITION for condition nodes.  It is modified using CAS
jaroslav@1890
   428
         * (or when possible, unconditional volatile writes).
jaroslav@1890
   429
         */
jaroslav@1890
   430
        volatile int waitStatus;
jaroslav@1890
   431
jaroslav@1890
   432
        /**
jaroslav@1890
   433
         * Link to predecessor node that current node/thread relies on
jaroslav@1890
   434
         * for checking waitStatus. Assigned during enqueing, and nulled
jaroslav@1890
   435
         * out (for sake of GC) only upon dequeuing.  Also, upon
jaroslav@1890
   436
         * cancellation of a predecessor, we short-circuit while
jaroslav@1890
   437
         * finding a non-cancelled one, which will always exist
jaroslav@1890
   438
         * because the head node is never cancelled: A node becomes
jaroslav@1890
   439
         * head only as a result of successful acquire. A
jaroslav@1890
   440
         * cancelled thread never succeeds in acquiring, and a thread only
jaroslav@1890
   441
         * cancels itself, not any other node.
jaroslav@1890
   442
         */
jaroslav@1890
   443
        volatile Node prev;
jaroslav@1890
   444
jaroslav@1890
   445
        /**
jaroslav@1890
   446
         * Link to the successor node that the current node/thread
jaroslav@1890
   447
         * unparks upon release. Assigned during enqueuing, adjusted
jaroslav@1890
   448
         * when bypassing cancelled predecessors, and nulled out (for
jaroslav@1890
   449
         * sake of GC) when dequeued.  The enq operation does not
jaroslav@1890
   450
         * assign next field of a predecessor until after attachment,
jaroslav@1890
   451
         * so seeing a null next field does not necessarily mean that
jaroslav@1890
   452
         * node is at end of queue. However, if a next field appears
jaroslav@1890
   453
         * to be null, we can scan prev's from the tail to
jaroslav@1890
   454
         * double-check.  The next field of cancelled nodes is set to
jaroslav@1890
   455
         * point to the node itself instead of null, to make life
jaroslav@1890
   456
         * easier for isOnSyncQueue.
jaroslav@1890
   457
         */
jaroslav@1890
   458
        volatile Node next;
jaroslav@1890
   459
jaroslav@1890
   460
        /**
jaroslav@1890
   461
         * The thread that enqueued this node.  Initialized on
jaroslav@1890
   462
         * construction and nulled out after use.
jaroslav@1890
   463
         */
jaroslav@1890
   464
        volatile Thread thread;
jaroslav@1890
   465
jaroslav@1890
   466
        /**
jaroslav@1890
   467
         * Link to next node waiting on condition, or the special
jaroslav@1890
   468
         * value SHARED.  Because condition queues are accessed only
jaroslav@1890
   469
         * when holding in exclusive mode, we just need a simple
jaroslav@1890
   470
         * linked queue to hold nodes while they are waiting on
jaroslav@1890
   471
         * conditions. They are then transferred to the queue to
jaroslav@1890
   472
         * re-acquire. And because conditions can only be exclusive,
jaroslav@1890
   473
         * we save a field by using special value to indicate shared
jaroslav@1890
   474
         * mode.
jaroslav@1890
   475
         */
jaroslav@1890
   476
        Node nextWaiter;
jaroslav@1890
   477
jaroslav@1890
   478
        /**
jaroslav@1890
   479
         * Returns true if node is waiting in shared mode
jaroslav@1890
   480
         */
jaroslav@1890
   481
        final boolean isShared() {
jaroslav@1890
   482
            return nextWaiter == SHARED;
jaroslav@1890
   483
        }
jaroslav@1890
   484
jaroslav@1890
   485
        /**
jaroslav@1890
   486
         * Returns previous node, or throws NullPointerException if null.
jaroslav@1890
   487
         * Use when predecessor cannot be null.  The null check could
jaroslav@1890
   488
         * be elided, but is present to help the VM.
jaroslav@1890
   489
         *
jaroslav@1890
   490
         * @return the predecessor of this node
jaroslav@1890
   491
         */
jaroslav@1890
   492
        final Node predecessor() throws NullPointerException {
jaroslav@1890
   493
            Node p = prev;
jaroslav@1890
   494
            if (p == null)
jaroslav@1890
   495
                throw new NullPointerException();
jaroslav@1890
   496
            else
jaroslav@1890
   497
                return p;
jaroslav@1890
   498
        }
jaroslav@1890
   499
jaroslav@1890
   500
        Node() {    // Used to establish initial head or SHARED marker
jaroslav@1890
   501
        }
jaroslav@1890
   502
jaroslav@1890
   503
        Node(Thread thread, Node mode) {     // Used by addWaiter
jaroslav@1890
   504
            this.nextWaiter = mode;
jaroslav@1890
   505
            this.thread = thread;
jaroslav@1890
   506
        }
jaroslav@1890
   507
jaroslav@1890
   508
        Node(Thread thread, int waitStatus) { // Used by Condition
jaroslav@1890
   509
            this.waitStatus = waitStatus;
jaroslav@1890
   510
            this.thread = thread;
jaroslav@1890
   511
        }
jaroslav@1890
   512
    }
jaroslav@1890
   513
jaroslav@1890
   514
    /**
jaroslav@1890
   515
     * Head of the wait queue, lazily initialized.  Except for
jaroslav@1890
   516
     * initialization, it is modified only via method setHead.  Note:
jaroslav@1890
   517
     * If head exists, its waitStatus is guaranteed not to be
jaroslav@1890
   518
     * CANCELLED.
jaroslav@1890
   519
     */
jaroslav@1890
   520
    private transient volatile Node head;
jaroslav@1890
   521
jaroslav@1890
   522
    /**
jaroslav@1890
   523
     * Tail of the wait queue, lazily initialized.  Modified only via
jaroslav@1890
   524
     * method enq to add new wait node.
jaroslav@1890
   525
     */
jaroslav@1890
   526
    private transient volatile Node tail;
jaroslav@1890
   527
jaroslav@1890
   528
    /**
jaroslav@1890
   529
     * The synchronization state.
jaroslav@1890
   530
     */
jaroslav@1890
   531
    private volatile int state;
jaroslav@1890
   532
jaroslav@1890
   533
    /**
jaroslav@1890
   534
     * Returns the current value of synchronization state.
jaroslav@1890
   535
     * This operation has memory semantics of a <tt>volatile</tt> read.
jaroslav@1890
   536
     * @return current state value
jaroslav@1890
   537
     */
jaroslav@1890
   538
    protected final int getState() {
jaroslav@1890
   539
        return state;
jaroslav@1890
   540
    }
jaroslav@1890
   541
jaroslav@1890
   542
    /**
jaroslav@1890
   543
     * Sets the value of synchronization state.
jaroslav@1890
   544
     * This operation has memory semantics of a <tt>volatile</tt> write.
jaroslav@1890
   545
     * @param newState the new state value
jaroslav@1890
   546
     */
jaroslav@1890
   547
    protected final void setState(int newState) {
jaroslav@1890
   548
        state = newState;
jaroslav@1890
   549
    }
jaroslav@1890
   550
jaroslav@1890
   551
    /**
jaroslav@1890
   552
     * Atomically sets synchronization state to the given updated
jaroslav@1890
   553
     * value if the current state value equals the expected value.
jaroslav@1890
   554
     * This operation has memory semantics of a <tt>volatile</tt> read
jaroslav@1890
   555
     * and write.
jaroslav@1890
   556
     *
jaroslav@1890
   557
     * @param expect the expected value
jaroslav@1890
   558
     * @param update the new value
jaroslav@1890
   559
     * @return true if successful. False return indicates that the actual
jaroslav@1890
   560
     *         value was not equal to the expected value.
jaroslav@1890
   561
     */
jaroslav@1890
   562
    protected final boolean compareAndSetState(int expect, int update) {
jaroslav@1890
   563
        // See below for intrinsics setup to support this
jaroslav@1894
   564
        if (this.state == expect) {
jaroslav@1894
   565
            this.state = update;
jaroslav@1894
   566
            return true;
jaroslav@1894
   567
        }
jaroslav@1894
   568
        return false;
jaroslav@1890
   569
    }
jaroslav@1890
   570
jaroslav@1890
   571
    // Queuing utilities
jaroslav@1890
   572
jaroslav@1890
   573
    /**
jaroslav@1890
   574
     * The number of nanoseconds for which it is faster to spin
jaroslav@1890
   575
     * rather than to use timed park. A rough estimate suffices
jaroslav@1890
   576
     * to improve responsiveness with very short timeouts.
jaroslav@1890
   577
     */
jaroslav@1890
   578
    static final long spinForTimeoutThreshold = 1000L;
jaroslav@1890
   579
jaroslav@1890
   580
    /**
jaroslav@1890
   581
     * Inserts node into queue, initializing if necessary. See picture above.
jaroslav@1890
   582
     * @param node the node to insert
jaroslav@1890
   583
     * @return node's predecessor
jaroslav@1890
   584
     */
jaroslav@1890
   585
    private Node enq(final Node node) {
jaroslav@1890
   586
        for (;;) {
jaroslav@1890
   587
            Node t = tail;
jaroslav@1890
   588
            if (t == null) { // Must initialize
jaroslav@1890
   589
                if (compareAndSetHead(new Node()))
jaroslav@1890
   590
                    tail = head;
jaroslav@1890
   591
            } else {
jaroslav@1890
   592
                node.prev = t;
jaroslav@1890
   593
                if (compareAndSetTail(t, node)) {
jaroslav@1890
   594
                    t.next = node;
jaroslav@1890
   595
                    return t;
jaroslav@1890
   596
                }
jaroslav@1890
   597
            }
jaroslav@1890
   598
        }
jaroslav@1890
   599
    }
jaroslav@1890
   600
jaroslav@1890
   601
    /**
jaroslav@1890
   602
     * Creates and enqueues node for current thread and given mode.
jaroslav@1890
   603
     *
jaroslav@1890
   604
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
jaroslav@1890
   605
     * @return the new node
jaroslav@1890
   606
     */
jaroslav@1890
   607
    private Node addWaiter(Node mode) {
jaroslav@1890
   608
        Node node = new Node(Thread.currentThread(), mode);
jaroslav@1890
   609
        // Try the fast path of enq; backup to full enq on failure
jaroslav@1890
   610
        Node pred = tail;
jaroslav@1890
   611
        if (pred != null) {
jaroslav@1890
   612
            node.prev = pred;
jaroslav@1890
   613
            if (compareAndSetTail(pred, node)) {
jaroslav@1890
   614
                pred.next = node;
jaroslav@1890
   615
                return node;
jaroslav@1890
   616
            }
jaroslav@1890
   617
        }
jaroslav@1890
   618
        enq(node);
jaroslav@1890
   619
        return node;
jaroslav@1890
   620
    }
jaroslav@1890
   621
jaroslav@1890
   622
    /**
jaroslav@1890
   623
     * Sets head of queue to be node, thus dequeuing. Called only by
jaroslav@1890
   624
     * acquire methods.  Also nulls out unused fields for sake of GC
jaroslav@1890
   625
     * and to suppress unnecessary signals and traversals.
jaroslav@1890
   626
     *
jaroslav@1890
   627
     * @param node the node
jaroslav@1890
   628
     */
jaroslav@1890
   629
    private void setHead(Node node) {
jaroslav@1890
   630
        head = node;
jaroslav@1890
   631
        node.thread = null;
jaroslav@1890
   632
        node.prev = null;
jaroslav@1890
   633
    }
jaroslav@1890
   634
jaroslav@1890
   635
    /**
jaroslav@1890
   636
     * Wakes up node's successor, if one exists.
jaroslav@1890
   637
     *
jaroslav@1890
   638
     * @param node the node
jaroslav@1890
   639
     */
jaroslav@1890
   640
    private void unparkSuccessor(Node node) {
jaroslav@1890
   641
        /*
jaroslav@1890
   642
         * If status is negative (i.e., possibly needing signal) try
jaroslav@1890
   643
         * to clear in anticipation of signalling.  It is OK if this
jaroslav@1890
   644
         * fails or if status is changed by waiting thread.
jaroslav@1890
   645
         */
jaroslav@1890
   646
        int ws = node.waitStatus;
jaroslav@1890
   647
        if (ws < 0)
jaroslav@1890
   648
            compareAndSetWaitStatus(node, ws, 0);
jaroslav@1890
   649
jaroslav@1890
   650
        /*
jaroslav@1890
   651
         * Thread to unpark is held in successor, which is normally
jaroslav@1890
   652
         * just the next node.  But if cancelled or apparently null,
jaroslav@1890
   653
         * traverse backwards from tail to find the actual
jaroslav@1890
   654
         * non-cancelled successor.
jaroslav@1890
   655
         */
jaroslav@1890
   656
        Node s = node.next;
jaroslav@1890
   657
        if (s == null || s.waitStatus > 0) {
jaroslav@1890
   658
            s = null;
jaroslav@1890
   659
            for (Node t = tail; t != null && t != node; t = t.prev)
jaroslav@1890
   660
                if (t.waitStatus <= 0)
jaroslav@1890
   661
                    s = t;
jaroslav@1890
   662
        }
jaroslav@1890
   663
        if (s != null)
jaroslav@1890
   664
            LockSupport.unpark(s.thread);
jaroslav@1890
   665
    }
jaroslav@1890
   666
jaroslav@1890
   667
    /**
jaroslav@1890
   668
     * Release action for shared mode -- signal successor and ensure
jaroslav@1890
   669
     * propagation. (Note: For exclusive mode, release just amounts
jaroslav@1890
   670
     * to calling unparkSuccessor of head if it needs signal.)
jaroslav@1890
   671
     */
jaroslav@1890
   672
    private void doReleaseShared() {
jaroslav@1890
   673
        /*
jaroslav@1890
   674
         * Ensure that a release propagates, even if there are other
jaroslav@1890
   675
         * in-progress acquires/releases.  This proceeds in the usual
jaroslav@1890
   676
         * way of trying to unparkSuccessor of head if it needs
jaroslav@1890
   677
         * signal. But if it does not, status is set to PROPAGATE to
jaroslav@1890
   678
         * ensure that upon release, propagation continues.
jaroslav@1890
   679
         * Additionally, we must loop in case a new node is added
jaroslav@1890
   680
         * while we are doing this. Also, unlike other uses of
jaroslav@1890
   681
         * unparkSuccessor, we need to know if CAS to reset status
jaroslav@1890
   682
         * fails, if so rechecking.
jaroslav@1890
   683
         */
jaroslav@1890
   684
        for (;;) {
jaroslav@1890
   685
            Node h = head;
jaroslav@1890
   686
            if (h != null && h != tail) {
jaroslav@1890
   687
                int ws = h.waitStatus;
jaroslav@1890
   688
                if (ws == Node.SIGNAL) {
jaroslav@1890
   689
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
jaroslav@1890
   690
                        continue;            // loop to recheck cases
jaroslav@1890
   691
                    unparkSuccessor(h);
jaroslav@1890
   692
                }
jaroslav@1890
   693
                else if (ws == 0 &&
jaroslav@1890
   694
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
jaroslav@1890
   695
                    continue;                // loop on failed CAS
jaroslav@1890
   696
            }
jaroslav@1890
   697
            if (h == head)                   // loop if head changed
jaroslav@1890
   698
                break;
jaroslav@1890
   699
        }
jaroslav@1890
   700
    }
jaroslav@1890
   701
jaroslav@1890
   702
    /**
jaroslav@1890
   703
     * Sets head of queue, and checks if successor may be waiting
jaroslav@1890
   704
     * in shared mode, if so propagating if either propagate > 0 or
jaroslav@1890
   705
     * PROPAGATE status was set.
jaroslav@1890
   706
     *
jaroslav@1890
   707
     * @param node the node
jaroslav@1890
   708
     * @param propagate the return value from a tryAcquireShared
jaroslav@1890
   709
     */
jaroslav@1890
   710
    private void setHeadAndPropagate(Node node, int propagate) {
jaroslav@1890
   711
        Node h = head; // Record old head for check below
jaroslav@1890
   712
        setHead(node);
jaroslav@1890
   713
        /*
jaroslav@1890
   714
         * Try to signal next queued node if:
jaroslav@1890
   715
         *   Propagation was indicated by caller,
jaroslav@1890
   716
         *     or was recorded (as h.waitStatus) by a previous operation
jaroslav@1890
   717
         *     (note: this uses sign-check of waitStatus because
jaroslav@1890
   718
         *      PROPAGATE status may transition to SIGNAL.)
jaroslav@1890
   719
         * and
jaroslav@1890
   720
         *   The next node is waiting in shared mode,
jaroslav@1890
   721
         *     or we don't know, because it appears null
jaroslav@1890
   722
         *
jaroslav@1890
   723
         * The conservatism in both of these checks may cause
jaroslav@1890
   724
         * unnecessary wake-ups, but only when there are multiple
jaroslav@1890
   725
         * racing acquires/releases, so most need signals now or soon
jaroslav@1890
   726
         * anyway.
jaroslav@1890
   727
         */
jaroslav@1890
   728
        if (propagate > 0 || h == null || h.waitStatus < 0) {
jaroslav@1890
   729
            Node s = node.next;
jaroslav@1890
   730
            if (s == null || s.isShared())
jaroslav@1890
   731
                doReleaseShared();
jaroslav@1890
   732
        }
jaroslav@1890
   733
    }
jaroslav@1890
   734
jaroslav@1890
   735
    // Utilities for various versions of acquire
jaroslav@1890
   736
jaroslav@1890
   737
    /**
jaroslav@1890
   738
     * Cancels an ongoing attempt to acquire.
jaroslav@1890
   739
     *
jaroslav@1890
   740
     * @param node the node
jaroslav@1890
   741
     */
jaroslav@1890
   742
    private void cancelAcquire(Node node) {
jaroslav@1890
   743
        // Ignore if node doesn't exist
jaroslav@1890
   744
        if (node == null)
jaroslav@1890
   745
            return;
jaroslav@1890
   746
jaroslav@1890
   747
        node.thread = null;
jaroslav@1890
   748
jaroslav@1890
   749
        // Skip cancelled predecessors
jaroslav@1890
   750
        Node pred = node.prev;
jaroslav@1890
   751
        while (pred.waitStatus > 0)
jaroslav@1890
   752
            node.prev = pred = pred.prev;
jaroslav@1890
   753
jaroslav@1890
   754
        // predNext is the apparent node to unsplice. CASes below will
jaroslav@1890
   755
        // fail if not, in which case, we lost race vs another cancel
jaroslav@1890
   756
        // or signal, so no further action is necessary.
jaroslav@1890
   757
        Node predNext = pred.next;
jaroslav@1890
   758
jaroslav@1890
   759
        // Can use unconditional write instead of CAS here.
jaroslav@1890
   760
        // After this atomic step, other Nodes can skip past us.
jaroslav@1890
   761
        // Before, we are free of interference from other threads.
jaroslav@1890
   762
        node.waitStatus = Node.CANCELLED;
jaroslav@1890
   763
jaroslav@1890
   764
        // If we are the tail, remove ourselves.
jaroslav@1890
   765
        if (node == tail && compareAndSetTail(node, pred)) {
jaroslav@1890
   766
            compareAndSetNext(pred, predNext, null);
jaroslav@1890
   767
        } else {
jaroslav@1890
   768
            // If successor needs signal, try to set pred's next-link
jaroslav@1890
   769
            // so it will get one. Otherwise wake it up to propagate.
jaroslav@1890
   770
            int ws;
jaroslav@1890
   771
            if (pred != head &&
jaroslav@1890
   772
                ((ws = pred.waitStatus) == Node.SIGNAL ||
jaroslav@1890
   773
                 (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
jaroslav@1890
   774
                pred.thread != null) {
jaroslav@1890
   775
                Node next = node.next;
jaroslav@1890
   776
                if (next != null && next.waitStatus <= 0)
jaroslav@1890
   777
                    compareAndSetNext(pred, predNext, next);
jaroslav@1890
   778
            } else {
jaroslav@1890
   779
                unparkSuccessor(node);
jaroslav@1890
   780
            }
jaroslav@1890
   781
jaroslav@1890
   782
            node.next = node; // help GC
jaroslav@1890
   783
        }
jaroslav@1890
   784
    }
jaroslav@1890
   785
jaroslav@1890
   786
    /**
jaroslav@1890
   787
     * Checks and updates status for a node that failed to acquire.
jaroslav@1890
   788
     * Returns true if thread should block. This is the main signal
jaroslav@1890
   789
     * control in all acquire loops.  Requires that pred == node.prev
jaroslav@1890
   790
     *
jaroslav@1890
   791
     * @param pred node's predecessor holding status
jaroslav@1890
   792
     * @param node the node
jaroslav@1890
   793
     * @return {@code true} if thread should block
jaroslav@1890
   794
     */
jaroslav@1890
   795
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
jaroslav@1890
   796
        int ws = pred.waitStatus;
jaroslav@1890
   797
        if (ws == Node.SIGNAL)
jaroslav@1890
   798
            /*
jaroslav@1890
   799
             * This node has already set status asking a release
jaroslav@1890
   800
             * to signal it, so it can safely park.
jaroslav@1890
   801
             */
jaroslav@1890
   802
            return true;
jaroslav@1890
   803
        if (ws > 0) {
jaroslav@1890
   804
            /*
jaroslav@1890
   805
             * Predecessor was cancelled. Skip over predecessors and
jaroslav@1890
   806
             * indicate retry.
jaroslav@1890
   807
             */
jaroslav@1890
   808
            do {
jaroslav@1890
   809
                node.prev = pred = pred.prev;
jaroslav@1890
   810
            } while (pred.waitStatus > 0);
jaroslav@1890
   811
            pred.next = node;
jaroslav@1890
   812
        } else {
jaroslav@1890
   813
            /*
jaroslav@1890
   814
             * waitStatus must be 0 or PROPAGATE.  Indicate that we
jaroslav@1890
   815
             * need a signal, but don't park yet.  Caller will need to
jaroslav@1890
   816
             * retry to make sure it cannot acquire before parking.
jaroslav@1890
   817
             */
jaroslav@1890
   818
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
jaroslav@1890
   819
        }
jaroslav@1890
   820
        return false;
jaroslav@1890
   821
    }
jaroslav@1890
   822
jaroslav@1890
   823
    /**
jaroslav@1890
   824
     * Convenience method to interrupt current thread.
jaroslav@1890
   825
     */
jaroslav@1890
   826
    private static void selfInterrupt() {
jaroslav@1890
   827
        Thread.currentThread().interrupt();
jaroslav@1890
   828
    }
jaroslav@1890
   829
jaroslav@1890
   830
    /**
jaroslav@1890
   831
     * Convenience method to park and then check if interrupted
jaroslav@1890
   832
     *
jaroslav@1890
   833
     * @return {@code true} if interrupted
jaroslav@1890
   834
     */
jaroslav@1890
   835
    private final boolean parkAndCheckInterrupt() {
jaroslav@1890
   836
        LockSupport.park(this);
jaroslav@1890
   837
        return Thread.interrupted();
jaroslav@1890
   838
    }
jaroslav@1890
   839
jaroslav@1890
   840
    /*
jaroslav@1890
   841
     * Various flavors of acquire, varying in exclusive/shared and
jaroslav@1890
   842
     * control modes.  Each is mostly the same, but annoyingly
jaroslav@1890
   843
     * different.  Only a little bit of factoring is possible due to
jaroslav@1890
   844
     * interactions of exception mechanics (including ensuring that we
jaroslav@1890
   845
     * cancel if tryAcquire throws exception) and other control, at
jaroslav@1890
   846
     * least not without hurting performance too much.
jaroslav@1890
   847
     */
jaroslav@1890
   848
jaroslav@1890
   849
    /**
jaroslav@1890
   850
     * Acquires in exclusive uninterruptible mode for thread already in
jaroslav@1890
   851
     * queue. Used by condition wait methods as well as acquire.
jaroslav@1890
   852
     *
jaroslav@1890
   853
     * @param node the node
jaroslav@1890
   854
     * @param arg the acquire argument
jaroslav@1890
   855
     * @return {@code true} if interrupted while waiting
jaroslav@1890
   856
     */
jaroslav@1890
   857
    final boolean acquireQueued(final Node node, int arg) {
jaroslav@1890
   858
        boolean failed = true;
jaroslav@1890
   859
        try {
jaroslav@1890
   860
            boolean interrupted = false;
jaroslav@1890
   861
            for (;;) {
jaroslav@1890
   862
                final Node p = node.predecessor();
jaroslav@1890
   863
                if (p == head && tryAcquire(arg)) {
jaroslav@1890
   864
                    setHead(node);
jaroslav@1890
   865
                    p.next = null; // help GC
jaroslav@1890
   866
                    failed = false;
jaroslav@1890
   867
                    return interrupted;
jaroslav@1890
   868
                }
jaroslav@1890
   869
                if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890
   870
                    parkAndCheckInterrupt())
jaroslav@1890
   871
                    interrupted = true;
jaroslav@1890
   872
            }
jaroslav@1890
   873
        } finally {
jaroslav@1890
   874
            if (failed)
jaroslav@1890
   875
                cancelAcquire(node);
jaroslav@1890
   876
        }
jaroslav@1890
   877
    }
jaroslav@1890
   878
jaroslav@1890
   879
    /**
jaroslav@1890
   880
     * Acquires in exclusive interruptible mode.
jaroslav@1890
   881
     * @param arg the acquire argument
jaroslav@1890
   882
     */
jaroslav@1890
   883
    private void doAcquireInterruptibly(int arg)
jaroslav@1890
   884
        throws InterruptedException {
jaroslav@1890
   885
        final Node node = addWaiter(Node.EXCLUSIVE);
jaroslav@1890
   886
        boolean failed = true;
jaroslav@1890
   887
        try {
jaroslav@1890
   888
            for (;;) {
jaroslav@1890
   889
                final Node p = node.predecessor();
jaroslav@1890
   890
                if (p == head && tryAcquire(arg)) {
jaroslav@1890
   891
                    setHead(node);
jaroslav@1890
   892
                    p.next = null; // help GC
jaroslav@1890
   893
                    failed = false;
jaroslav@1890
   894
                    return;
jaroslav@1890
   895
                }
jaroslav@1890
   896
                if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890
   897
                    parkAndCheckInterrupt())
jaroslav@1890
   898
                    throw new InterruptedException();
jaroslav@1890
   899
            }
jaroslav@1890
   900
        } finally {
jaroslav@1890
   901
            if (failed)
jaroslav@1890
   902
                cancelAcquire(node);
jaroslav@1890
   903
        }
jaroslav@1890
   904
    }
jaroslav@1890
   905
jaroslav@1890
   906
    /**
jaroslav@1890
   907
     * Acquires in exclusive timed mode.
jaroslav@1890
   908
     *
jaroslav@1890
   909
     * @param arg the acquire argument
jaroslav@1890
   910
     * @param nanosTimeout max wait time
jaroslav@1890
   911
     * @return {@code true} if acquired
jaroslav@1890
   912
     */
jaroslav@1890
   913
    private boolean doAcquireNanos(int arg, long nanosTimeout)
jaroslav@1890
   914
        throws InterruptedException {
jaroslav@1890
   915
        long lastTime = System.nanoTime();
jaroslav@1890
   916
        final Node node = addWaiter(Node.EXCLUSIVE);
jaroslav@1890
   917
        boolean failed = true;
jaroslav@1890
   918
        try {
jaroslav@1890
   919
            for (;;) {
jaroslav@1890
   920
                final Node p = node.predecessor();
jaroslav@1890
   921
                if (p == head && tryAcquire(arg)) {
jaroslav@1890
   922
                    setHead(node);
jaroslav@1890
   923
                    p.next = null; // help GC
jaroslav@1890
   924
                    failed = false;
jaroslav@1890
   925
                    return true;
jaroslav@1890
   926
                }
jaroslav@1890
   927
                if (nanosTimeout <= 0)
jaroslav@1890
   928
                    return false;
jaroslav@1890
   929
                if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890
   930
                    nanosTimeout > spinForTimeoutThreshold)
jaroslav@1890
   931
                    LockSupport.parkNanos(this, nanosTimeout);
jaroslav@1890
   932
                long now = System.nanoTime();
jaroslav@1890
   933
                nanosTimeout -= now - lastTime;
jaroslav@1890
   934
                lastTime = now;
jaroslav@1890
   935
                if (Thread.interrupted())
jaroslav@1890
   936
                    throw new InterruptedException();
jaroslav@1890
   937
            }
jaroslav@1890
   938
        } finally {
jaroslav@1890
   939
            if (failed)
jaroslav@1890
   940
                cancelAcquire(node);
jaroslav@1890
   941
        }
jaroslav@1890
   942
    }
jaroslav@1890
   943
jaroslav@1890
   944
    /**
jaroslav@1890
   945
     * Acquires in shared uninterruptible mode.
jaroslav@1890
   946
     * @param arg the acquire argument
jaroslav@1890
   947
     */
jaroslav@1890
   948
    private void doAcquireShared(int arg) {
jaroslav@1890
   949
        final Node node = addWaiter(Node.SHARED);
jaroslav@1890
   950
        boolean failed = true;
jaroslav@1890
   951
        try {
jaroslav@1890
   952
            boolean interrupted = false;
jaroslav@1890
   953
            for (;;) {
jaroslav@1890
   954
                final Node p = node.predecessor();
jaroslav@1890
   955
                if (p == head) {
jaroslav@1890
   956
                    int r = tryAcquireShared(arg);
jaroslav@1890
   957
                    if (r >= 0) {
jaroslav@1890
   958
                        setHeadAndPropagate(node, r);
jaroslav@1890
   959
                        p.next = null; // help GC
jaroslav@1890
   960
                        if (interrupted)
jaroslav@1890
   961
                            selfInterrupt();
jaroslav@1890
   962
                        failed = false;
jaroslav@1890
   963
                        return;
jaroslav@1890
   964
                    }
jaroslav@1890
   965
                }
jaroslav@1890
   966
                if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890
   967
                    parkAndCheckInterrupt())
jaroslav@1890
   968
                    interrupted = true;
jaroslav@1890
   969
            }
jaroslav@1890
   970
        } finally {
jaroslav@1890
   971
            if (failed)
jaroslav@1890
   972
                cancelAcquire(node);
jaroslav@1890
   973
        }
jaroslav@1890
   974
    }
jaroslav@1890
   975
jaroslav@1890
   976
    /**
jaroslav@1890
   977
     * Acquires in shared interruptible mode.
jaroslav@1890
   978
     * @param arg the acquire argument
jaroslav@1890
   979
     */
jaroslav@1890
   980
    private void doAcquireSharedInterruptibly(int arg)
jaroslav@1890
   981
        throws InterruptedException {
jaroslav@1890
   982
        final Node node = addWaiter(Node.SHARED);
jaroslav@1890
   983
        boolean failed = true;
jaroslav@1890
   984
        try {
jaroslav@1890
   985
            for (;;) {
jaroslav@1890
   986
                final Node p = node.predecessor();
jaroslav@1890
   987
                if (p == head) {
jaroslav@1890
   988
                    int r = tryAcquireShared(arg);
jaroslav@1890
   989
                    if (r >= 0) {
jaroslav@1890
   990
                        setHeadAndPropagate(node, r);
jaroslav@1890
   991
                        p.next = null; // help GC
jaroslav@1890
   992
                        failed = false;
jaroslav@1890
   993
                        return;
jaroslav@1890
   994
                    }
jaroslav@1890
   995
                }
jaroslav@1890
   996
                if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890
   997
                    parkAndCheckInterrupt())
jaroslav@1890
   998
                    throw new InterruptedException();
jaroslav@1890
   999
            }
jaroslav@1890
  1000
        } finally {
jaroslav@1890
  1001
            if (failed)
jaroslav@1890
  1002
                cancelAcquire(node);
jaroslav@1890
  1003
        }
jaroslav@1890
  1004
    }
jaroslav@1890
  1005
jaroslav@1890
  1006
    /**
jaroslav@1890
  1007
     * Acquires in shared timed mode.
jaroslav@1890
  1008
     *
jaroslav@1890
  1009
     * @param arg the acquire argument
jaroslav@1890
  1010
     * @param nanosTimeout max wait time
jaroslav@1890
  1011
     * @return {@code true} if acquired
jaroslav@1890
  1012
     */
jaroslav@1890
  1013
    private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
jaroslav@1890
  1014
        throws InterruptedException {
jaroslav@1890
  1015
jaroslav@1890
  1016
        long lastTime = System.nanoTime();
jaroslav@1890
  1017
        final Node node = addWaiter(Node.SHARED);
jaroslav@1890
  1018
        boolean failed = true;
jaroslav@1890
  1019
        try {
jaroslav@1890
  1020
            for (;;) {
jaroslav@1890
  1021
                final Node p = node.predecessor();
jaroslav@1890
  1022
                if (p == head) {
jaroslav@1890
  1023
                    int r = tryAcquireShared(arg);
jaroslav@1890
  1024
                    if (r >= 0) {
jaroslav@1890
  1025
                        setHeadAndPropagate(node, r);
jaroslav@1890
  1026
                        p.next = null; // help GC
jaroslav@1890
  1027
                        failed = false;
jaroslav@1890
  1028
                        return true;
jaroslav@1890
  1029
                    }
jaroslav@1890
  1030
                }
jaroslav@1890
  1031
                if (nanosTimeout <= 0)
jaroslav@1890
  1032
                    return false;
jaroslav@1890
  1033
                if (shouldParkAfterFailedAcquire(p, node) &&
jaroslav@1890
  1034
                    nanosTimeout > spinForTimeoutThreshold)
jaroslav@1890
  1035
                    LockSupport.parkNanos(this, nanosTimeout);
jaroslav@1890
  1036
                long now = System.nanoTime();
jaroslav@1890
  1037
                nanosTimeout -= now - lastTime;
jaroslav@1890
  1038
                lastTime = now;
jaroslav@1890
  1039
                if (Thread.interrupted())
jaroslav@1890
  1040
                    throw new InterruptedException();
jaroslav@1890
  1041
            }
jaroslav@1890
  1042
        } finally {
jaroslav@1890
  1043
            if (failed)
jaroslav@1890
  1044
                cancelAcquire(node);
jaroslav@1890
  1045
        }
jaroslav@1890
  1046
    }
jaroslav@1890
  1047
jaroslav@1890
  1048
    // Main exported methods
jaroslav@1890
  1049
jaroslav@1890
  1050
    /**
jaroslav@1890
  1051
     * Attempts to acquire in exclusive mode. This method should query
jaroslav@1890
  1052
     * if the state of the object permits it to be acquired in the
jaroslav@1890
  1053
     * exclusive mode, and if so to acquire it.
jaroslav@1890
  1054
     *
jaroslav@1890
  1055
     * <p>This method is always invoked by the thread performing
jaroslav@1890
  1056
     * acquire.  If this method reports failure, the acquire method
jaroslav@1890
  1057
     * may queue the thread, if it is not already queued, until it is
jaroslav@1890
  1058
     * signalled by a release from some other thread. This can be used
jaroslav@1890
  1059
     * to implement method {@link Lock#tryLock()}.
jaroslav@1890
  1060
     *
jaroslav@1890
  1061
     * <p>The default
jaroslav@1890
  1062
     * implementation throws {@link UnsupportedOperationException}.
jaroslav@1890
  1063
     *
jaroslav@1890
  1064
     * @param arg the acquire argument. This value is always the one
jaroslav@1890
  1065
     *        passed to an acquire method, or is the value saved on entry
jaroslav@1890
  1066
     *        to a condition wait.  The value is otherwise uninterpreted
jaroslav@1890
  1067
     *        and can represent anything you like.
jaroslav@1890
  1068
     * @return {@code true} if successful. Upon success, this object has
jaroslav@1890
  1069
     *         been acquired.
jaroslav@1890
  1070
     * @throws IllegalMonitorStateException if acquiring would place this
jaroslav@1890
  1071
     *         synchronizer in an illegal state. This exception must be
jaroslav@1890
  1072
     *         thrown in a consistent fashion for synchronization to work
jaroslav@1890
  1073
     *         correctly.
jaroslav@1890
  1074
     * @throws UnsupportedOperationException if exclusive mode is not supported
jaroslav@1890
  1075
     */
jaroslav@1890
  1076
    protected boolean tryAcquire(int arg) {
jaroslav@1890
  1077
        throw new UnsupportedOperationException();
jaroslav@1890
  1078
    }
jaroslav@1890
  1079
jaroslav@1890
  1080
    /**
jaroslav@1890
  1081
     * Attempts to set the state to reflect a release in exclusive
jaroslav@1890
  1082
     * mode.
jaroslav@1890
  1083
     *
jaroslav@1890
  1084
     * <p>This method is always invoked by the thread performing release.
jaroslav@1890
  1085
     *
jaroslav@1890
  1086
     * <p>The default implementation throws
jaroslav@1890
  1087
     * {@link UnsupportedOperationException}.
jaroslav@1890
  1088
     *
jaroslav@1890
  1089
     * @param arg the release argument. This value is always the one
jaroslav@1890
  1090
     *        passed to a release method, or the current state value upon
jaroslav@1890
  1091
     *        entry to a condition wait.  The value is otherwise
jaroslav@1890
  1092
     *        uninterpreted and can represent anything you like.
jaroslav@1890
  1093
     * @return {@code true} if this object is now in a fully released
jaroslav@1890
  1094
     *         state, so that any waiting threads may attempt to acquire;
jaroslav@1890
  1095
     *         and {@code false} otherwise.
jaroslav@1890
  1096
     * @throws IllegalMonitorStateException if releasing would place this
jaroslav@1890
  1097
     *         synchronizer in an illegal state. This exception must be
jaroslav@1890
  1098
     *         thrown in a consistent fashion for synchronization to work
jaroslav@1890
  1099
     *         correctly.
jaroslav@1890
  1100
     * @throws UnsupportedOperationException if exclusive mode is not supported
jaroslav@1890
  1101
     */
jaroslav@1890
  1102
    protected boolean tryRelease(int arg) {
jaroslav@1890
  1103
        throw new UnsupportedOperationException();
jaroslav@1890
  1104
    }
jaroslav@1890
  1105
jaroslav@1890
  1106
    /**
jaroslav@1890
  1107
     * Attempts to acquire in shared mode. This method should query if
jaroslav@1890
  1108
     * the state of the object permits it to be acquired in the shared
jaroslav@1890
  1109
     * mode, and if so to acquire it.
jaroslav@1890
  1110
     *
jaroslav@1890
  1111
     * <p>This method is always invoked by the thread performing
jaroslav@1890
  1112
     * acquire.  If this method reports failure, the acquire method
jaroslav@1890
  1113
     * may queue the thread, if it is not already queued, until it is
jaroslav@1890
  1114
     * signalled by a release from some other thread.
jaroslav@1890
  1115
     *
jaroslav@1890
  1116
     * <p>The default implementation throws {@link
jaroslav@1890
  1117
     * UnsupportedOperationException}.
jaroslav@1890
  1118
     *
jaroslav@1890
  1119
     * @param arg the acquire argument. This value is always the one
jaroslav@1890
  1120
     *        passed to an acquire method, or is the value saved on entry
jaroslav@1890
  1121
     *        to a condition wait.  The value is otherwise uninterpreted
jaroslav@1890
  1122
     *        and can represent anything you like.
jaroslav@1890
  1123
     * @return a negative value on failure; zero if acquisition in shared
jaroslav@1890
  1124
     *         mode succeeded but no subsequent shared-mode acquire can
jaroslav@1890
  1125
     *         succeed; and a positive value if acquisition in shared
jaroslav@1890
  1126
     *         mode succeeded and subsequent shared-mode acquires might
jaroslav@1890
  1127
     *         also succeed, in which case a subsequent waiting thread
jaroslav@1890
  1128
     *         must check availability. (Support for three different
jaroslav@1890
  1129
     *         return values enables this method to be used in contexts
jaroslav@1890
  1130
     *         where acquires only sometimes act exclusively.)  Upon
jaroslav@1890
  1131
     *         success, this object has been acquired.
jaroslav@1890
  1132
     * @throws IllegalMonitorStateException if acquiring would place this
jaroslav@1890
  1133
     *         synchronizer in an illegal state. This exception must be
jaroslav@1890
  1134
     *         thrown in a consistent fashion for synchronization to work
jaroslav@1890
  1135
     *         correctly.
jaroslav@1890
  1136
     * @throws UnsupportedOperationException if shared mode is not supported
jaroslav@1890
  1137
     */
jaroslav@1890
  1138
    protected int tryAcquireShared(int arg) {
jaroslav@1890
  1139
        throw new UnsupportedOperationException();
jaroslav@1890
  1140
    }
jaroslav@1890
  1141
jaroslav@1890
  1142
    /**
jaroslav@1890
  1143
     * Attempts to set the state to reflect a release in shared mode.
jaroslav@1890
  1144
     *
jaroslav@1890
  1145
     * <p>This method is always invoked by the thread performing release.
jaroslav@1890
  1146
     *
jaroslav@1890
  1147
     * <p>The default implementation throws
jaroslav@1890
  1148
     * {@link UnsupportedOperationException}.
jaroslav@1890
  1149
     *
jaroslav@1890
  1150
     * @param arg the release argument. This value is always the one
jaroslav@1890
  1151
     *        passed to a release method, or the current state value upon
jaroslav@1890
  1152
     *        entry to a condition wait.  The value is otherwise
jaroslav@1890
  1153
     *        uninterpreted and can represent anything you like.
jaroslav@1890
  1154
     * @return {@code true} if this release of shared mode may permit a
jaroslav@1890
  1155
     *         waiting acquire (shared or exclusive) to succeed; and
jaroslav@1890
  1156
     *         {@code false} otherwise
jaroslav@1890
  1157
     * @throws IllegalMonitorStateException if releasing would place this
jaroslav@1890
  1158
     *         synchronizer in an illegal state. This exception must be
jaroslav@1890
  1159
     *         thrown in a consistent fashion for synchronization to work
jaroslav@1890
  1160
     *         correctly.
jaroslav@1890
  1161
     * @throws UnsupportedOperationException if shared mode is not supported
jaroslav@1890
  1162
     */
jaroslav@1890
  1163
    protected boolean tryReleaseShared(int arg) {
jaroslav@1890
  1164
        throw new UnsupportedOperationException();
jaroslav@1890
  1165
    }
jaroslav@1890
  1166
jaroslav@1890
  1167
    /**
jaroslav@1890
  1168
     * Returns {@code true} if synchronization is held exclusively with
jaroslav@1890
  1169
     * respect to the current (calling) thread.  This method is invoked
jaroslav@1890
  1170
     * upon each call to a non-waiting {@link ConditionObject} method.
jaroslav@1890
  1171
     * (Waiting methods instead invoke {@link #release}.)
jaroslav@1890
  1172
     *
jaroslav@1890
  1173
     * <p>The default implementation throws {@link
jaroslav@1890
  1174
     * UnsupportedOperationException}. This method is invoked
jaroslav@1890
  1175
     * internally only within {@link ConditionObject} methods, so need
jaroslav@1890
  1176
     * not be defined if conditions are not used.
jaroslav@1890
  1177
     *
jaroslav@1890
  1178
     * @return {@code true} if synchronization is held exclusively;
jaroslav@1890
  1179
     *         {@code false} otherwise
jaroslav@1890
  1180
     * @throws UnsupportedOperationException if conditions are not supported
jaroslav@1890
  1181
     */
jaroslav@1890
  1182
    protected boolean isHeldExclusively() {
jaroslav@1890
  1183
        throw new UnsupportedOperationException();
jaroslav@1890
  1184
    }
jaroslav@1890
  1185
jaroslav@1890
  1186
    /**
jaroslav@1890
  1187
     * Acquires in exclusive mode, ignoring interrupts.  Implemented
jaroslav@1890
  1188
     * by invoking at least once {@link #tryAcquire},
jaroslav@1890
  1189
     * returning on success.  Otherwise the thread is queued, possibly
jaroslav@1890
  1190
     * repeatedly blocking and unblocking, invoking {@link
jaroslav@1890
  1191
     * #tryAcquire} until success.  This method can be used
jaroslav@1890
  1192
     * to implement method {@link Lock#lock}.
jaroslav@1890
  1193
     *
jaroslav@1890
  1194
     * @param arg the acquire argument.  This value is conveyed to
jaroslav@1890
  1195
     *        {@link #tryAcquire} but is otherwise uninterpreted and
jaroslav@1890
  1196
     *        can represent anything you like.
jaroslav@1890
  1197
     */
jaroslav@1890
  1198
    public final void acquire(int arg) {
jaroslav@1890
  1199
        if (!tryAcquire(arg) &&
jaroslav@1890
  1200
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
jaroslav@1890
  1201
            selfInterrupt();
jaroslav@1890
  1202
    }
jaroslav@1890
  1203
jaroslav@1890
  1204
    /**
jaroslav@1890
  1205
     * Acquires in exclusive mode, aborting if interrupted.
jaroslav@1890
  1206
     * Implemented by first checking interrupt status, then invoking
jaroslav@1890
  1207
     * at least once {@link #tryAcquire}, returning on
jaroslav@1890
  1208
     * success.  Otherwise the thread is queued, possibly repeatedly
jaroslav@1890
  1209
     * blocking and unblocking, invoking {@link #tryAcquire}
jaroslav@1890
  1210
     * until success or the thread is interrupted.  This method can be
jaroslav@1890
  1211
     * used to implement method {@link Lock#lockInterruptibly}.
jaroslav@1890
  1212
     *
jaroslav@1890
  1213
     * @param arg the acquire argument.  This value is conveyed to
jaroslav@1890
  1214
     *        {@link #tryAcquire} but is otherwise uninterpreted and
jaroslav@1890
  1215
     *        can represent anything you like.
jaroslav@1890
  1216
     * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
  1217
     */
jaroslav@1890
  1218
    public final void acquireInterruptibly(int arg)
jaroslav@1890
  1219
            throws InterruptedException {
jaroslav@1890
  1220
        if (Thread.interrupted())
jaroslav@1890
  1221
            throw new InterruptedException();
jaroslav@1890
  1222
        if (!tryAcquire(arg))
jaroslav@1890
  1223
            doAcquireInterruptibly(arg);
jaroslav@1890
  1224
    }
jaroslav@1890
  1225
jaroslav@1890
  1226
    /**
jaroslav@1890
  1227
     * Attempts to acquire in exclusive mode, aborting if interrupted,
jaroslav@1890
  1228
     * and failing if the given timeout elapses.  Implemented by first
jaroslav@1890
  1229
     * checking interrupt status, then invoking at least once {@link
jaroslav@1890
  1230
     * #tryAcquire}, returning on success.  Otherwise, the thread is
jaroslav@1890
  1231
     * queued, possibly repeatedly blocking and unblocking, invoking
jaroslav@1890
  1232
     * {@link #tryAcquire} until success or the thread is interrupted
jaroslav@1890
  1233
     * or the timeout elapses.  This method can be used to implement
jaroslav@1890
  1234
     * method {@link Lock#tryLock(long, TimeUnit)}.
jaroslav@1890
  1235
     *
jaroslav@1890
  1236
     * @param arg the acquire argument.  This value is conveyed to
jaroslav@1890
  1237
     *        {@link #tryAcquire} but is otherwise uninterpreted and
jaroslav@1890
  1238
     *        can represent anything you like.
jaroslav@1890
  1239
     * @param nanosTimeout the maximum number of nanoseconds to wait
jaroslav@1890
  1240
     * @return {@code true} if acquired; {@code false} if timed out
jaroslav@1890
  1241
     * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
  1242
     */
jaroslav@1890
  1243
    public final boolean tryAcquireNanos(int arg, long nanosTimeout)
jaroslav@1890
  1244
            throws InterruptedException {
jaroslav@1890
  1245
        if (Thread.interrupted())
jaroslav@1890
  1246
            throw new InterruptedException();
jaroslav@1890
  1247
        return tryAcquire(arg) ||
jaroslav@1890
  1248
            doAcquireNanos(arg, nanosTimeout);
jaroslav@1890
  1249
    }
jaroslav@1890
  1250
jaroslav@1890
  1251
    /**
jaroslav@1890
  1252
     * Releases in exclusive mode.  Implemented by unblocking one or
jaroslav@1890
  1253
     * more threads if {@link #tryRelease} returns true.
jaroslav@1890
  1254
     * This method can be used to implement method {@link Lock#unlock}.
jaroslav@1890
  1255
     *
jaroslav@1890
  1256
     * @param arg the release argument.  This value is conveyed to
jaroslav@1890
  1257
     *        {@link #tryRelease} but is otherwise uninterpreted and
jaroslav@1890
  1258
     *        can represent anything you like.
jaroslav@1890
  1259
     * @return the value returned from {@link #tryRelease}
jaroslav@1890
  1260
     */
jaroslav@1890
  1261
    public final boolean release(int arg) {
jaroslav@1890
  1262
        if (tryRelease(arg)) {
jaroslav@1890
  1263
            Node h = head;
jaroslav@1890
  1264
            if (h != null && h.waitStatus != 0)
jaroslav@1890
  1265
                unparkSuccessor(h);
jaroslav@1890
  1266
            return true;
jaroslav@1890
  1267
        }
jaroslav@1890
  1268
        return false;
jaroslav@1890
  1269
    }
jaroslav@1890
  1270
jaroslav@1890
  1271
    /**
jaroslav@1890
  1272
     * Acquires in shared mode, ignoring interrupts.  Implemented by
jaroslav@1890
  1273
     * first invoking at least once {@link #tryAcquireShared},
jaroslav@1890
  1274
     * returning on success.  Otherwise the thread is queued, possibly
jaroslav@1890
  1275
     * repeatedly blocking and unblocking, invoking {@link
jaroslav@1890
  1276
     * #tryAcquireShared} until success.
jaroslav@1890
  1277
     *
jaroslav@1890
  1278
     * @param arg the acquire argument.  This value is conveyed to
jaroslav@1890
  1279
     *        {@link #tryAcquireShared} but is otherwise uninterpreted
jaroslav@1890
  1280
     *        and can represent anything you like.
jaroslav@1890
  1281
     */
jaroslav@1890
  1282
    public final void acquireShared(int arg) {
jaroslav@1890
  1283
        if (tryAcquireShared(arg) < 0)
jaroslav@1890
  1284
            doAcquireShared(arg);
jaroslav@1890
  1285
    }
jaroslav@1890
  1286
jaroslav@1890
  1287
    /**
jaroslav@1890
  1288
     * Acquires in shared mode, aborting if interrupted.  Implemented
jaroslav@1890
  1289
     * by first checking interrupt status, then invoking at least once
jaroslav@1890
  1290
     * {@link #tryAcquireShared}, returning on success.  Otherwise the
jaroslav@1890
  1291
     * thread is queued, possibly repeatedly blocking and unblocking,
jaroslav@1890
  1292
     * invoking {@link #tryAcquireShared} until success or the thread
jaroslav@1890
  1293
     * is interrupted.
jaroslav@1890
  1294
     * @param arg the acquire argument
jaroslav@1890
  1295
     * This value is conveyed to {@link #tryAcquireShared} but is
jaroslav@1890
  1296
     * otherwise uninterpreted and can represent anything
jaroslav@1890
  1297
     * you like.
jaroslav@1890
  1298
     * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
  1299
     */
jaroslav@1890
  1300
    public final void acquireSharedInterruptibly(int arg)
jaroslav@1890
  1301
            throws InterruptedException {
jaroslav@1890
  1302
        if (Thread.interrupted())
jaroslav@1890
  1303
            throw new InterruptedException();
jaroslav@1890
  1304
        if (tryAcquireShared(arg) < 0)
jaroslav@1890
  1305
            doAcquireSharedInterruptibly(arg);
jaroslav@1890
  1306
    }
jaroslav@1890
  1307
jaroslav@1890
  1308
    /**
jaroslav@1890
  1309
     * Attempts to acquire in shared mode, aborting if interrupted, and
jaroslav@1890
  1310
     * failing if the given timeout elapses.  Implemented by first
jaroslav@1890
  1311
     * checking interrupt status, then invoking at least once {@link
jaroslav@1890
  1312
     * #tryAcquireShared}, returning on success.  Otherwise, the
jaroslav@1890
  1313
     * thread is queued, possibly repeatedly blocking and unblocking,
jaroslav@1890
  1314
     * invoking {@link #tryAcquireShared} until success or the thread
jaroslav@1890
  1315
     * is interrupted or the timeout elapses.
jaroslav@1890
  1316
     *
jaroslav@1890
  1317
     * @param arg the acquire argument.  This value is conveyed to
jaroslav@1890
  1318
     *        {@link #tryAcquireShared} but is otherwise uninterpreted
jaroslav@1890
  1319
     *        and can represent anything you like.
jaroslav@1890
  1320
     * @param nanosTimeout the maximum number of nanoseconds to wait
jaroslav@1890
  1321
     * @return {@code true} if acquired; {@code false} if timed out
jaroslav@1890
  1322
     * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
  1323
     */
jaroslav@1890
  1324
    public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
jaroslav@1890
  1325
            throws InterruptedException {
jaroslav@1890
  1326
        if (Thread.interrupted())
jaroslav@1890
  1327
            throw new InterruptedException();
jaroslav@1890
  1328
        return tryAcquireShared(arg) >= 0 ||
jaroslav@1890
  1329
            doAcquireSharedNanos(arg, nanosTimeout);
jaroslav@1890
  1330
    }
jaroslav@1890
  1331
jaroslav@1890
  1332
    /**
jaroslav@1890
  1333
     * Releases in shared mode.  Implemented by unblocking one or more
jaroslav@1890
  1334
     * threads if {@link #tryReleaseShared} returns true.
jaroslav@1890
  1335
     *
jaroslav@1890
  1336
     * @param arg the release argument.  This value is conveyed to
jaroslav@1890
  1337
     *        {@link #tryReleaseShared} but is otherwise uninterpreted
jaroslav@1890
  1338
     *        and can represent anything you like.
jaroslav@1890
  1339
     * @return the value returned from {@link #tryReleaseShared}
jaroslav@1890
  1340
     */
jaroslav@1890
  1341
    public final boolean releaseShared(int arg) {
jaroslav@1890
  1342
        if (tryReleaseShared(arg)) {
jaroslav@1890
  1343
            doReleaseShared();
jaroslav@1890
  1344
            return true;
jaroslav@1890
  1345
        }
jaroslav@1890
  1346
        return false;
jaroslav@1890
  1347
    }
jaroslav@1890
  1348
jaroslav@1890
  1349
    // Queue inspection methods
jaroslav@1890
  1350
jaroslav@1890
  1351
    /**
jaroslav@1890
  1352
     * Queries whether any threads are waiting to acquire. Note that
jaroslav@1890
  1353
     * because cancellations due to interrupts and timeouts may occur
jaroslav@1890
  1354
     * at any time, a {@code true} return does not guarantee that any
jaroslav@1890
  1355
     * other thread will ever acquire.
jaroslav@1890
  1356
     *
jaroslav@1890
  1357
     * <p>In this implementation, this operation returns in
jaroslav@1890
  1358
     * constant time.
jaroslav@1890
  1359
     *
jaroslav@1890
  1360
     * @return {@code true} if there may be other threads waiting to acquire
jaroslav@1890
  1361
     */
jaroslav@1890
  1362
    public final boolean hasQueuedThreads() {
jaroslav@1890
  1363
        return head != tail;
jaroslav@1890
  1364
    }
jaroslav@1890
  1365
jaroslav@1890
  1366
    /**
jaroslav@1890
  1367
     * Queries whether any threads have ever contended to acquire this
jaroslav@1890
  1368
     * synchronizer; that is if an acquire method has ever blocked.
jaroslav@1890
  1369
     *
jaroslav@1890
  1370
     * <p>In this implementation, this operation returns in
jaroslav@1890
  1371
     * constant time.
jaroslav@1890
  1372
     *
jaroslav@1890
  1373
     * @return {@code true} if there has ever been contention
jaroslav@1890
  1374
     */
jaroslav@1890
  1375
    public final boolean hasContended() {
jaroslav@1890
  1376
        return head != null;
jaroslav@1890
  1377
    }
jaroslav@1890
  1378
jaroslav@1890
  1379
    /**
jaroslav@1890
  1380
     * Returns the first (longest-waiting) thread in the queue, or
jaroslav@1890
  1381
     * {@code null} if no threads are currently queued.
jaroslav@1890
  1382
     *
jaroslav@1890
  1383
     * <p>In this implementation, this operation normally returns in
jaroslav@1890
  1384
     * constant time, but may iterate upon contention if other threads are
jaroslav@1890
  1385
     * concurrently modifying the queue.
jaroslav@1890
  1386
     *
jaroslav@1890
  1387
     * @return the first (longest-waiting) thread in the queue, or
jaroslav@1890
  1388
     *         {@code null} if no threads are currently queued
jaroslav@1890
  1389
     */
jaroslav@1890
  1390
    public final Thread getFirstQueuedThread() {
jaroslav@1890
  1391
        // handle only fast path, else relay
jaroslav@1890
  1392
        return (head == tail) ? null : fullGetFirstQueuedThread();
jaroslav@1890
  1393
    }
jaroslav@1890
  1394
jaroslav@1890
  1395
    /**
jaroslav@1890
  1396
     * Version of getFirstQueuedThread called when fastpath fails
jaroslav@1890
  1397
     */
jaroslav@1890
  1398
    private Thread fullGetFirstQueuedThread() {
jaroslav@1890
  1399
        /*
jaroslav@1890
  1400
         * The first node is normally head.next. Try to get its
jaroslav@1890
  1401
         * thread field, ensuring consistent reads: If thread
jaroslav@1890
  1402
         * field is nulled out or s.prev is no longer head, then
jaroslav@1890
  1403
         * some other thread(s) concurrently performed setHead in
jaroslav@1890
  1404
         * between some of our reads. We try this twice before
jaroslav@1890
  1405
         * resorting to traversal.
jaroslav@1890
  1406
         */
jaroslav@1890
  1407
        Node h, s;
jaroslav@1890
  1408
        Thread st;
jaroslav@1890
  1409
        if (((h = head) != null && (s = h.next) != null &&
jaroslav@1890
  1410
             s.prev == head && (st = s.thread) != null) ||
jaroslav@1890
  1411
            ((h = head) != null && (s = h.next) != null &&
jaroslav@1890
  1412
             s.prev == head && (st = s.thread) != null))
jaroslav@1890
  1413
            return st;
jaroslav@1890
  1414
jaroslav@1890
  1415
        /*
jaroslav@1890
  1416
         * Head's next field might not have been set yet, or may have
jaroslav@1890
  1417
         * been unset after setHead. So we must check to see if tail
jaroslav@1890
  1418
         * is actually first node. If not, we continue on, safely
jaroslav@1890
  1419
         * traversing from tail back to head to find first,
jaroslav@1890
  1420
         * guaranteeing termination.
jaroslav@1890
  1421
         */
jaroslav@1890
  1422
jaroslav@1890
  1423
        Node t = tail;
jaroslav@1890
  1424
        Thread firstThread = null;
jaroslav@1890
  1425
        while (t != null && t != head) {
jaroslav@1890
  1426
            Thread tt = t.thread;
jaroslav@1890
  1427
            if (tt != null)
jaroslav@1890
  1428
                firstThread = tt;
jaroslav@1890
  1429
            t = t.prev;
jaroslav@1890
  1430
        }
jaroslav@1890
  1431
        return firstThread;
jaroslav@1890
  1432
    }
jaroslav@1890
  1433
jaroslav@1890
  1434
    /**
jaroslav@1890
  1435
     * Returns true if the given thread is currently queued.
jaroslav@1890
  1436
     *
jaroslav@1890
  1437
     * <p>This implementation traverses the queue to determine
jaroslav@1890
  1438
     * presence of the given thread.
jaroslav@1890
  1439
     *
jaroslav@1890
  1440
     * @param thread the thread
jaroslav@1890
  1441
     * @return {@code true} if the given thread is on the queue
jaroslav@1890
  1442
     * @throws NullPointerException if the thread is null
jaroslav@1890
  1443
     */
jaroslav@1890
  1444
    public final boolean isQueued(Thread thread) {
jaroslav@1890
  1445
        if (thread == null)
jaroslav@1890
  1446
            throw new NullPointerException();
jaroslav@1890
  1447
        for (Node p = tail; p != null; p = p.prev)
jaroslav@1890
  1448
            if (p.thread == thread)
jaroslav@1890
  1449
                return true;
jaroslav@1890
  1450
        return false;
jaroslav@1890
  1451
    }
jaroslav@1890
  1452
jaroslav@1890
  1453
    /**
jaroslav@1890
  1454
     * Returns {@code true} if the apparent first queued thread, if one
jaroslav@1890
  1455
     * exists, is waiting in exclusive mode.  If this method returns
jaroslav@1890
  1456
     * {@code true}, and the current thread is attempting to acquire in
jaroslav@1890
  1457
     * shared mode (that is, this method is invoked from {@link
jaroslav@1890
  1458
     * #tryAcquireShared}) then it is guaranteed that the current thread
jaroslav@1890
  1459
     * is not the first queued thread.  Used only as a heuristic in
jaroslav@1890
  1460
     * ReentrantReadWriteLock.
jaroslav@1890
  1461
     */
jaroslav@1890
  1462
    final boolean apparentlyFirstQueuedIsExclusive() {
jaroslav@1890
  1463
        Node h, s;
jaroslav@1890
  1464
        return (h = head) != null &&
jaroslav@1890
  1465
            (s = h.next)  != null &&
jaroslav@1890
  1466
            !s.isShared()         &&
jaroslav@1890
  1467
            s.thread != null;
jaroslav@1890
  1468
    }
jaroslav@1890
  1469
jaroslav@1890
  1470
    /**
jaroslav@1890
  1471
     * Queries whether any threads have been waiting to acquire longer
jaroslav@1890
  1472
     * than the current thread.
jaroslav@1890
  1473
     *
jaroslav@1890
  1474
     * <p>An invocation of this method is equivalent to (but may be
jaroslav@1890
  1475
     * more efficient than):
jaroslav@1890
  1476
     *  <pre> {@code
jaroslav@1890
  1477
     * getFirstQueuedThread() != Thread.currentThread() &&
jaroslav@1890
  1478
     * hasQueuedThreads()}</pre>
jaroslav@1890
  1479
     *
jaroslav@1890
  1480
     * <p>Note that because cancellations due to interrupts and
jaroslav@1890
  1481
     * timeouts may occur at any time, a {@code true} return does not
jaroslav@1890
  1482
     * guarantee that some other thread will acquire before the current
jaroslav@1890
  1483
     * thread.  Likewise, it is possible for another thread to win a
jaroslav@1890
  1484
     * race to enqueue after this method has returned {@code false},
jaroslav@1890
  1485
     * due to the queue being empty.
jaroslav@1890
  1486
     *
jaroslav@1890
  1487
     * <p>This method is designed to be used by a fair synchronizer to
jaroslav@1890
  1488
     * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>.
jaroslav@1890
  1489
     * Such a synchronizer's {@link #tryAcquire} method should return
jaroslav@1890
  1490
     * {@code false}, and its {@link #tryAcquireShared} method should
jaroslav@1890
  1491
     * return a negative value, if this method returns {@code true}
jaroslav@1890
  1492
     * (unless this is a reentrant acquire).  For example, the {@code
jaroslav@1890
  1493
     * tryAcquire} method for a fair, reentrant, exclusive mode
jaroslav@1890
  1494
     * synchronizer might look like this:
jaroslav@1890
  1495
     *
jaroslav@1890
  1496
     *  <pre> {@code
jaroslav@1890
  1497
     * protected boolean tryAcquire(int arg) {
jaroslav@1890
  1498
     *   if (isHeldExclusively()) {
jaroslav@1890
  1499
     *     // A reentrant acquire; increment hold count
jaroslav@1890
  1500
     *     return true;
jaroslav@1890
  1501
     *   } else if (hasQueuedPredecessors()) {
jaroslav@1890
  1502
     *     return false;
jaroslav@1890
  1503
     *   } else {
jaroslav@1890
  1504
     *     // try to acquire normally
jaroslav@1890
  1505
     *   }
jaroslav@1890
  1506
     * }}</pre>
jaroslav@1890
  1507
     *
jaroslav@1890
  1508
     * @return {@code true} if there is a queued thread preceding the
jaroslav@1890
  1509
     *         current thread, and {@code false} if the current thread
jaroslav@1890
  1510
     *         is at the head of the queue or the queue is empty
jaroslav@1890
  1511
     * @since 1.7
jaroslav@1890
  1512
     */
jaroslav@1890
  1513
    public final boolean hasQueuedPredecessors() {
jaroslav@1890
  1514
        // The correctness of this depends on head being initialized
jaroslav@1890
  1515
        // before tail and on head.next being accurate if the current
jaroslav@1890
  1516
        // thread is first in queue.
jaroslav@1890
  1517
        Node t = tail; // Read fields in reverse initialization order
jaroslav@1890
  1518
        Node h = head;
jaroslav@1890
  1519
        Node s;
jaroslav@1890
  1520
        return h != t &&
jaroslav@1890
  1521
            ((s = h.next) == null || s.thread != Thread.currentThread());
jaroslav@1890
  1522
    }
jaroslav@1890
  1523
jaroslav@1890
  1524
jaroslav@1890
  1525
    // Instrumentation and monitoring methods
jaroslav@1890
  1526
jaroslav@1890
  1527
    /**
jaroslav@1890
  1528
     * Returns an estimate of the number of threads waiting to
jaroslav@1890
  1529
     * acquire.  The value is only an estimate because the number of
jaroslav@1890
  1530
     * threads may change dynamically while this method traverses
jaroslav@1890
  1531
     * internal data structures.  This method is designed for use in
jaroslav@1890
  1532
     * monitoring system state, not for synchronization
jaroslav@1890
  1533
     * control.
jaroslav@1890
  1534
     *
jaroslav@1890
  1535
     * @return the estimated number of threads waiting to acquire
jaroslav@1890
  1536
     */
jaroslav@1890
  1537
    public final int getQueueLength() {
jaroslav@1890
  1538
        int n = 0;
jaroslav@1890
  1539
        for (Node p = tail; p != null; p = p.prev) {
jaroslav@1890
  1540
            if (p.thread != null)
jaroslav@1890
  1541
                ++n;
jaroslav@1890
  1542
        }
jaroslav@1890
  1543
        return n;
jaroslav@1890
  1544
    }
jaroslav@1890
  1545
jaroslav@1890
  1546
    /**
jaroslav@1890
  1547
     * Returns a collection containing threads that may be waiting to
jaroslav@1890
  1548
     * acquire.  Because the actual set of threads may change
jaroslav@1890
  1549
     * dynamically while constructing this result, the returned
jaroslav@1890
  1550
     * collection is only a best-effort estimate.  The elements of the
jaroslav@1890
  1551
     * returned collection are in no particular order.  This method is
jaroslav@1890
  1552
     * designed to facilitate construction of subclasses that provide
jaroslav@1890
  1553
     * more extensive monitoring facilities.
jaroslav@1890
  1554
     *
jaroslav@1890
  1555
     * @return the collection of threads
jaroslav@1890
  1556
     */
jaroslav@1890
  1557
    public final Collection<Thread> getQueuedThreads() {
jaroslav@1890
  1558
        ArrayList<Thread> list = new ArrayList<Thread>();
jaroslav@1890
  1559
        for (Node p = tail; p != null; p = p.prev) {
jaroslav@1890
  1560
            Thread t = p.thread;
jaroslav@1890
  1561
            if (t != null)
jaroslav@1890
  1562
                list.add(t);
jaroslav@1890
  1563
        }
jaroslav@1890
  1564
        return list;
jaroslav@1890
  1565
    }
jaroslav@1890
  1566
jaroslav@1890
  1567
    /**
jaroslav@1890
  1568
     * Returns a collection containing threads that may be waiting to
jaroslav@1890
  1569
     * acquire in exclusive mode. This has the same properties
jaroslav@1890
  1570
     * as {@link #getQueuedThreads} except that it only returns
jaroslav@1890
  1571
     * those threads waiting due to an exclusive acquire.
jaroslav@1890
  1572
     *
jaroslav@1890
  1573
     * @return the collection of threads
jaroslav@1890
  1574
     */
jaroslav@1890
  1575
    public final Collection<Thread> getExclusiveQueuedThreads() {
jaroslav@1890
  1576
        ArrayList<Thread> list = new ArrayList<Thread>();
jaroslav@1890
  1577
        for (Node p = tail; p != null; p = p.prev) {
jaroslav@1890
  1578
            if (!p.isShared()) {
jaroslav@1890
  1579
                Thread t = p.thread;
jaroslav@1890
  1580
                if (t != null)
jaroslav@1890
  1581
                    list.add(t);
jaroslav@1890
  1582
            }
jaroslav@1890
  1583
        }
jaroslav@1890
  1584
        return list;
jaroslav@1890
  1585
    }
jaroslav@1890
  1586
jaroslav@1890
  1587
    /**
jaroslav@1890
  1588
     * Returns a collection containing threads that may be waiting to
jaroslav@1890
  1589
     * acquire in shared mode. This has the same properties
jaroslav@1890
  1590
     * as {@link #getQueuedThreads} except that it only returns
jaroslav@1890
  1591
     * those threads waiting due to a shared acquire.
jaroslav@1890
  1592
     *
jaroslav@1890
  1593
     * @return the collection of threads
jaroslav@1890
  1594
     */
jaroslav@1890
  1595
    public final Collection<Thread> getSharedQueuedThreads() {
jaroslav@1890
  1596
        ArrayList<Thread> list = new ArrayList<Thread>();
jaroslav@1890
  1597
        for (Node p = tail; p != null; p = p.prev) {
jaroslav@1890
  1598
            if (p.isShared()) {
jaroslav@1890
  1599
                Thread t = p.thread;
jaroslav@1890
  1600
                if (t != null)
jaroslav@1890
  1601
                    list.add(t);
jaroslav@1890
  1602
            }
jaroslav@1890
  1603
        }
jaroslav@1890
  1604
        return list;
jaroslav@1890
  1605
    }
jaroslav@1890
  1606
jaroslav@1890
  1607
    /**
jaroslav@1890
  1608
     * Returns a string identifying this synchronizer, as well as its state.
jaroslav@1890
  1609
     * The state, in brackets, includes the String {@code "State ="}
jaroslav@1890
  1610
     * followed by the current value of {@link #getState}, and either
jaroslav@1890
  1611
     * {@code "nonempty"} or {@code "empty"} depending on whether the
jaroslav@1890
  1612
     * queue is empty.
jaroslav@1890
  1613
     *
jaroslav@1890
  1614
     * @return a string identifying this synchronizer, as well as its state
jaroslav@1890
  1615
     */
jaroslav@1890
  1616
    public String toString() {
jaroslav@1890
  1617
        int s = getState();
jaroslav@1890
  1618
        String q  = hasQueuedThreads() ? "non" : "";
jaroslav@1890
  1619
        return super.toString() +
jaroslav@1890
  1620
            "[State = " + s + ", " + q + "empty queue]";
jaroslav@1890
  1621
    }
jaroslav@1890
  1622
jaroslav@1890
  1623
jaroslav@1890
  1624
    // Internal support methods for Conditions
jaroslav@1890
  1625
jaroslav@1890
  1626
    /**
jaroslav@1890
  1627
     * Returns true if a node, always one that was initially placed on
jaroslav@1890
  1628
     * a condition queue, is now waiting to reacquire on sync queue.
jaroslav@1890
  1629
     * @param node the node
jaroslav@1890
  1630
     * @return true if is reacquiring
jaroslav@1890
  1631
     */
jaroslav@1890
  1632
    final boolean isOnSyncQueue(Node node) {
jaroslav@1890
  1633
        if (node.waitStatus == Node.CONDITION || node.prev == null)
jaroslav@1890
  1634
            return false;
jaroslav@1890
  1635
        if (node.next != null) // If has successor, it must be on queue
jaroslav@1890
  1636
            return true;
jaroslav@1890
  1637
        /*
jaroslav@1890
  1638
         * node.prev can be non-null, but not yet on queue because
jaroslav@1890
  1639
         * the CAS to place it on queue can fail. So we have to
jaroslav@1890
  1640
         * traverse from tail to make sure it actually made it.  It
jaroslav@1890
  1641
         * will always be near the tail in calls to this method, and
jaroslav@1890
  1642
         * unless the CAS failed (which is unlikely), it will be
jaroslav@1890
  1643
         * there, so we hardly ever traverse much.
jaroslav@1890
  1644
         */
jaroslav@1890
  1645
        return findNodeFromTail(node);
jaroslav@1890
  1646
    }
jaroslav@1890
  1647
jaroslav@1890
  1648
    /**
jaroslav@1890
  1649
     * Returns true if node is on sync queue by searching backwards from tail.
jaroslav@1890
  1650
     * Called only when needed by isOnSyncQueue.
jaroslav@1890
  1651
     * @return true if present
jaroslav@1890
  1652
     */
jaroslav@1890
  1653
    private boolean findNodeFromTail(Node node) {
jaroslav@1890
  1654
        Node t = tail;
jaroslav@1890
  1655
        for (;;) {
jaroslav@1890
  1656
            if (t == node)
jaroslav@1890
  1657
                return true;
jaroslav@1890
  1658
            if (t == null)
jaroslav@1890
  1659
                return false;
jaroslav@1890
  1660
            t = t.prev;
jaroslav@1890
  1661
        }
jaroslav@1890
  1662
    }
jaroslav@1890
  1663
jaroslav@1890
  1664
    /**
jaroslav@1890
  1665
     * Transfers a node from a condition queue onto sync queue.
jaroslav@1890
  1666
     * Returns true if successful.
jaroslav@1890
  1667
     * @param node the node
jaroslav@1890
  1668
     * @return true if successfully transferred (else the node was
jaroslav@1890
  1669
     * cancelled before signal).
jaroslav@1890
  1670
     */
jaroslav@1890
  1671
    final boolean transferForSignal(Node node) {
jaroslav@1890
  1672
        /*
jaroslav@1890
  1673
         * If cannot change waitStatus, the node has been cancelled.
jaroslav@1890
  1674
         */
jaroslav@1890
  1675
        if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
jaroslav@1890
  1676
            return false;
jaroslav@1890
  1677
jaroslav@1890
  1678
        /*
jaroslav@1890
  1679
         * Splice onto queue and try to set waitStatus of predecessor to
jaroslav@1890
  1680
         * indicate that thread is (probably) waiting. If cancelled or
jaroslav@1890
  1681
         * attempt to set waitStatus fails, wake up to resync (in which
jaroslav@1890
  1682
         * case the waitStatus can be transiently and harmlessly wrong).
jaroslav@1890
  1683
         */
jaroslav@1890
  1684
        Node p = enq(node);
jaroslav@1890
  1685
        int ws = p.waitStatus;
jaroslav@1890
  1686
        if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
jaroslav@1890
  1687
            LockSupport.unpark(node.thread);
jaroslav@1890
  1688
        return true;
jaroslav@1890
  1689
    }
jaroslav@1890
  1690
jaroslav@1890
  1691
    /**
jaroslav@1890
  1692
     * Transfers node, if necessary, to sync queue after a cancelled
jaroslav@1890
  1693
     * wait. Returns true if thread was cancelled before being
jaroslav@1890
  1694
     * signalled.
jaroslav@1890
  1695
     * @param current the waiting thread
jaroslav@1890
  1696
     * @param node its node
jaroslav@1890
  1697
     * @return true if cancelled before the node was signalled
jaroslav@1890
  1698
     */
jaroslav@1890
  1699
    final boolean transferAfterCancelledWait(Node node) {
jaroslav@1890
  1700
        if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
jaroslav@1890
  1701
            enq(node);
jaroslav@1890
  1702
            return true;
jaroslav@1890
  1703
        }
jaroslav@1890
  1704
        /*
jaroslav@1890
  1705
         * If we lost out to a signal(), then we can't proceed
jaroslav@1890
  1706
         * until it finishes its enq().  Cancelling during an
jaroslav@1890
  1707
         * incomplete transfer is both rare and transient, so just
jaroslav@1890
  1708
         * spin.
jaroslav@1890
  1709
         */
jaroslav@1890
  1710
        while (!isOnSyncQueue(node))
jaroslav@1890
  1711
            Thread.yield();
jaroslav@1890
  1712
        return false;
jaroslav@1890
  1713
    }
jaroslav@1890
  1714
jaroslav@1890
  1715
    /**
jaroslav@1890
  1716
     * Invokes release with current state value; returns saved state.
jaroslav@1890
  1717
     * Cancels node and throws exception on failure.
jaroslav@1890
  1718
     * @param node the condition node for this wait
jaroslav@1890
  1719
     * @return previous sync state
jaroslav@1890
  1720
     */
jaroslav@1890
  1721
    final int fullyRelease(Node node) {
jaroslav@1890
  1722
        boolean failed = true;
jaroslav@1890
  1723
        try {
jaroslav@1890
  1724
            int savedState = getState();
jaroslav@1890
  1725
            if (release(savedState)) {
jaroslav@1890
  1726
                failed = false;
jaroslav@1890
  1727
                return savedState;
jaroslav@1890
  1728
            } else {
jaroslav@1890
  1729
                throw new IllegalMonitorStateException();
jaroslav@1890
  1730
            }
jaroslav@1890
  1731
        } finally {
jaroslav@1890
  1732
            if (failed)
jaroslav@1890
  1733
                node.waitStatus = Node.CANCELLED;
jaroslav@1890
  1734
        }
jaroslav@1890
  1735
    }
jaroslav@1890
  1736
jaroslav@1890
  1737
    // Instrumentation methods for conditions
jaroslav@1890
  1738
jaroslav@1890
  1739
    /**
jaroslav@1890
  1740
     * Queries whether the given ConditionObject
jaroslav@1890
  1741
     * uses this synchronizer as its lock.
jaroslav@1890
  1742
     *
jaroslav@1890
  1743
     * @param condition the condition
jaroslav@1890
  1744
     * @return <tt>true</tt> if owned
jaroslav@1890
  1745
     * @throws NullPointerException if the condition is null
jaroslav@1890
  1746
     */
jaroslav@1890
  1747
    public final boolean owns(ConditionObject condition) {
jaroslav@1890
  1748
        if (condition == null)
jaroslav@1890
  1749
            throw new NullPointerException();
jaroslav@1890
  1750
        return condition.isOwnedBy(this);
jaroslav@1890
  1751
    }
jaroslav@1890
  1752
jaroslav@1890
  1753
    /**
jaroslav@1890
  1754
     * Queries whether any threads are waiting on the given condition
jaroslav@1890
  1755
     * associated with this synchronizer. Note that because timeouts
jaroslav@1890
  1756
     * and interrupts may occur at any time, a <tt>true</tt> return
jaroslav@1890
  1757
     * does not guarantee that a future <tt>signal</tt> will awaken
jaroslav@1890
  1758
     * any threads.  This method is designed primarily for use in
jaroslav@1890
  1759
     * monitoring of the system state.
jaroslav@1890
  1760
     *
jaroslav@1890
  1761
     * @param condition the condition
jaroslav@1890
  1762
     * @return <tt>true</tt> if there are any waiting threads
jaroslav@1890
  1763
     * @throws IllegalMonitorStateException if exclusive synchronization
jaroslav@1890
  1764
     *         is not held
jaroslav@1890
  1765
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
  1766
     *         not associated with this synchronizer
jaroslav@1890
  1767
     * @throws NullPointerException if the condition is null
jaroslav@1890
  1768
     */
jaroslav@1890
  1769
    public final boolean hasWaiters(ConditionObject condition) {
jaroslav@1890
  1770
        if (!owns(condition))
jaroslav@1890
  1771
            throw new IllegalArgumentException("Not owner");
jaroslav@1890
  1772
        return condition.hasWaiters();
jaroslav@1890
  1773
    }
jaroslav@1890
  1774
jaroslav@1890
  1775
    /**
jaroslav@1890
  1776
     * Returns an estimate of the number of threads waiting on the
jaroslav@1890
  1777
     * given condition associated with this synchronizer. Note that
jaroslav@1890
  1778
     * because timeouts and interrupts may occur at any time, the
jaroslav@1890
  1779
     * estimate serves only as an upper bound on the actual number of
jaroslav@1890
  1780
     * waiters.  This method is designed for use in monitoring of the
jaroslav@1890
  1781
     * system state, not for synchronization control.
jaroslav@1890
  1782
     *
jaroslav@1890
  1783
     * @param condition the condition
jaroslav@1890
  1784
     * @return the estimated number of waiting threads
jaroslav@1890
  1785
     * @throws IllegalMonitorStateException if exclusive synchronization
jaroslav@1890
  1786
     *         is not held
jaroslav@1890
  1787
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
  1788
     *         not associated with this synchronizer
jaroslav@1890
  1789
     * @throws NullPointerException if the condition is null
jaroslav@1890
  1790
     */
jaroslav@1890
  1791
    public final int getWaitQueueLength(ConditionObject condition) {
jaroslav@1890
  1792
        if (!owns(condition))
jaroslav@1890
  1793
            throw new IllegalArgumentException("Not owner");
jaroslav@1890
  1794
        return condition.getWaitQueueLength();
jaroslav@1890
  1795
    }
jaroslav@1890
  1796
jaroslav@1890
  1797
    /**
jaroslav@1890
  1798
     * Returns a collection containing those threads that may be
jaroslav@1890
  1799
     * waiting on the given condition associated with this
jaroslav@1890
  1800
     * synchronizer.  Because the actual set of threads may change
jaroslav@1890
  1801
     * dynamically while constructing this result, the returned
jaroslav@1890
  1802
     * collection is only a best-effort estimate. The elements of the
jaroslav@1890
  1803
     * returned collection are in no particular order.
jaroslav@1890
  1804
     *
jaroslav@1890
  1805
     * @param condition the condition
jaroslav@1890
  1806
     * @return the collection of threads
jaroslav@1890
  1807
     * @throws IllegalMonitorStateException if exclusive synchronization
jaroslav@1890
  1808
     *         is not held
jaroslav@1890
  1809
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
  1810
     *         not associated with this synchronizer
jaroslav@1890
  1811
     * @throws NullPointerException if the condition is null
jaroslav@1890
  1812
     */
jaroslav@1890
  1813
    public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
jaroslav@1890
  1814
        if (!owns(condition))
jaroslav@1890
  1815
            throw new IllegalArgumentException("Not owner");
jaroslav@1890
  1816
        return condition.getWaitingThreads();
jaroslav@1890
  1817
    }
jaroslav@1890
  1818
jaroslav@1890
  1819
    /**
jaroslav@1890
  1820
     * Condition implementation for a {@link
jaroslav@1890
  1821
     * AbstractQueuedSynchronizer} serving as the basis of a {@link
jaroslav@1890
  1822
     * Lock} implementation.
jaroslav@1890
  1823
     *
jaroslav@1890
  1824
     * <p>Method documentation for this class describes mechanics,
jaroslav@1890
  1825
     * not behavioral specifications from the point of view of Lock
jaroslav@1890
  1826
     * and Condition users. Exported versions of this class will in
jaroslav@1890
  1827
     * general need to be accompanied by documentation describing
jaroslav@1890
  1828
     * condition semantics that rely on those of the associated
jaroslav@1890
  1829
     * <tt>AbstractQueuedSynchronizer</tt>.
jaroslav@1890
  1830
     *
jaroslav@1890
  1831
     * <p>This class is Serializable, but all fields are transient,
jaroslav@1890
  1832
     * so deserialized conditions have no waiters.
jaroslav@1890
  1833
     */
jaroslav@1890
  1834
    public class ConditionObject implements Condition, java.io.Serializable {
jaroslav@1890
  1835
        private static final long serialVersionUID = 1173984872572414699L;
jaroslav@1890
  1836
        /** First node of condition queue. */
jaroslav@1890
  1837
        private transient Node firstWaiter;
jaroslav@1890
  1838
        /** Last node of condition queue. */
jaroslav@1890
  1839
        private transient Node lastWaiter;
jaroslav@1890
  1840
jaroslav@1890
  1841
        /**
jaroslav@1890
  1842
         * Creates a new <tt>ConditionObject</tt> instance.
jaroslav@1890
  1843
         */
jaroslav@1890
  1844
        public ConditionObject() { }
jaroslav@1890
  1845
jaroslav@1890
  1846
        // Internal methods
jaroslav@1890
  1847
jaroslav@1890
  1848
        /**
jaroslav@1890
  1849
         * Adds a new waiter to wait queue.
jaroslav@1890
  1850
         * @return its new wait node
jaroslav@1890
  1851
         */
jaroslav@1890
  1852
        private Node addConditionWaiter() {
jaroslav@1890
  1853
            Node t = lastWaiter;
jaroslav@1890
  1854
            // If lastWaiter is cancelled, clean out.
jaroslav@1890
  1855
            if (t != null && t.waitStatus != Node.CONDITION) {
jaroslav@1890
  1856
                unlinkCancelledWaiters();
jaroslav@1890
  1857
                t = lastWaiter;
jaroslav@1890
  1858
            }
jaroslav@1890
  1859
            Node node = new Node(Thread.currentThread(), Node.CONDITION);
jaroslav@1890
  1860
            if (t == null)
jaroslav@1890
  1861
                firstWaiter = node;
jaroslav@1890
  1862
            else
jaroslav@1890
  1863
                t.nextWaiter = node;
jaroslav@1890
  1864
            lastWaiter = node;
jaroslav@1890
  1865
            return node;
jaroslav@1890
  1866
        }
jaroslav@1890
  1867
jaroslav@1890
  1868
        /**
jaroslav@1890
  1869
         * Removes and transfers nodes until hit non-cancelled one or
jaroslav@1890
  1870
         * null. Split out from signal in part to encourage compilers
jaroslav@1890
  1871
         * to inline the case of no waiters.
jaroslav@1890
  1872
         * @param first (non-null) the first node on condition queue
jaroslav@1890
  1873
         */
jaroslav@1890
  1874
        private void doSignal(Node first) {
jaroslav@1890
  1875
            do {
jaroslav@1890
  1876
                if ( (firstWaiter = first.nextWaiter) == null)
jaroslav@1890
  1877
                    lastWaiter = null;
jaroslav@1890
  1878
                first.nextWaiter = null;
jaroslav@1890
  1879
            } while (!transferForSignal(first) &&
jaroslav@1890
  1880
                     (first = firstWaiter) != null);
jaroslav@1890
  1881
        }
jaroslav@1890
  1882
jaroslav@1890
  1883
        /**
jaroslav@1890
  1884
         * Removes and transfers all nodes.
jaroslav@1890
  1885
         * @param first (non-null) the first node on condition queue
jaroslav@1890
  1886
         */
jaroslav@1890
  1887
        private void doSignalAll(Node first) {
jaroslav@1890
  1888
            lastWaiter = firstWaiter = null;
jaroslav@1890
  1889
            do {
jaroslav@1890
  1890
                Node next = first.nextWaiter;
jaroslav@1890
  1891
                first.nextWaiter = null;
jaroslav@1890
  1892
                transferForSignal(first);
jaroslav@1890
  1893
                first = next;
jaroslav@1890
  1894
            } while (first != null);
jaroslav@1890
  1895
        }
jaroslav@1890
  1896
jaroslav@1890
  1897
        /**
jaroslav@1890
  1898
         * Unlinks cancelled waiter nodes from condition queue.
jaroslav@1890
  1899
         * Called only while holding lock. This is called when
jaroslav@1890
  1900
         * cancellation occurred during condition wait, and upon
jaroslav@1890
  1901
         * insertion of a new waiter when lastWaiter is seen to have
jaroslav@1890
  1902
         * been cancelled. This method is needed to avoid garbage
jaroslav@1890
  1903
         * retention in the absence of signals. So even though it may
jaroslav@1890
  1904
         * require a full traversal, it comes into play only when
jaroslav@1890
  1905
         * timeouts or cancellations occur in the absence of
jaroslav@1890
  1906
         * signals. It traverses all nodes rather than stopping at a
jaroslav@1890
  1907
         * particular target to unlink all pointers to garbage nodes
jaroslav@1890
  1908
         * without requiring many re-traversals during cancellation
jaroslav@1890
  1909
         * storms.
jaroslav@1890
  1910
         */
jaroslav@1890
  1911
        private void unlinkCancelledWaiters() {
jaroslav@1890
  1912
            Node t = firstWaiter;
jaroslav@1890
  1913
            Node trail = null;
jaroslav@1890
  1914
            while (t != null) {
jaroslav@1890
  1915
                Node next = t.nextWaiter;
jaroslav@1890
  1916
                if (t.waitStatus != Node.CONDITION) {
jaroslav@1890
  1917
                    t.nextWaiter = null;
jaroslav@1890
  1918
                    if (trail == null)
jaroslav@1890
  1919
                        firstWaiter = next;
jaroslav@1890
  1920
                    else
jaroslav@1890
  1921
                        trail.nextWaiter = next;
jaroslav@1890
  1922
                    if (next == null)
jaroslav@1890
  1923
                        lastWaiter = trail;
jaroslav@1890
  1924
                }
jaroslav@1890
  1925
                else
jaroslav@1890
  1926
                    trail = t;
jaroslav@1890
  1927
                t = next;
jaroslav@1890
  1928
            }
jaroslav@1890
  1929
        }
jaroslav@1890
  1930
jaroslav@1890
  1931
        // public methods
jaroslav@1890
  1932
jaroslav@1890
  1933
        /**
jaroslav@1890
  1934
         * Moves the longest-waiting thread, if one exists, from the
jaroslav@1890
  1935
         * wait queue for this condition to the wait queue for the
jaroslav@1890
  1936
         * owning lock.
jaroslav@1890
  1937
         *
jaroslav@1890
  1938
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890
  1939
         *         returns {@code false}
jaroslav@1890
  1940
         */
jaroslav@1890
  1941
        public final void signal() {
jaroslav@1890
  1942
            if (!isHeldExclusively())
jaroslav@1890
  1943
                throw new IllegalMonitorStateException();
jaroslav@1890
  1944
            Node first = firstWaiter;
jaroslav@1890
  1945
            if (first != null)
jaroslav@1890
  1946
                doSignal(first);
jaroslav@1890
  1947
        }
jaroslav@1890
  1948
jaroslav@1890
  1949
        /**
jaroslav@1890
  1950
         * Moves all threads from the wait queue for this condition to
jaroslav@1890
  1951
         * the wait queue for the owning lock.
jaroslav@1890
  1952
         *
jaroslav@1890
  1953
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890
  1954
         *         returns {@code false}
jaroslav@1890
  1955
         */
jaroslav@1890
  1956
        public final void signalAll() {
jaroslav@1890
  1957
            if (!isHeldExclusively())
jaroslav@1890
  1958
                throw new IllegalMonitorStateException();
jaroslav@1890
  1959
            Node first = firstWaiter;
jaroslav@1890
  1960
            if (first != null)
jaroslav@1890
  1961
                doSignalAll(first);
jaroslav@1890
  1962
        }
jaroslav@1890
  1963
jaroslav@1890
  1964
        /**
jaroslav@1890
  1965
         * Implements uninterruptible condition wait.
jaroslav@1890
  1966
         * <ol>
jaroslav@1890
  1967
         * <li> Save lock state returned by {@link #getState}.
jaroslav@1890
  1968
         * <li> Invoke {@link #release} with
jaroslav@1890
  1969
         *      saved state as argument, throwing
jaroslav@1890
  1970
         *      IllegalMonitorStateException if it fails.
jaroslav@1890
  1971
         * <li> Block until signalled.
jaroslav@1890
  1972
         * <li> Reacquire by invoking specialized version of
jaroslav@1890
  1973
         *      {@link #acquire} with saved state as argument.
jaroslav@1890
  1974
         * </ol>
jaroslav@1890
  1975
         */
jaroslav@1890
  1976
        public final void awaitUninterruptibly() {
jaroslav@1890
  1977
            Node node = addConditionWaiter();
jaroslav@1890
  1978
            int savedState = fullyRelease(node);
jaroslav@1890
  1979
            boolean interrupted = false;
jaroslav@1890
  1980
            while (!isOnSyncQueue(node)) {
jaroslav@1890
  1981
                LockSupport.park(this);
jaroslav@1890
  1982
                if (Thread.interrupted())
jaroslav@1890
  1983
                    interrupted = true;
jaroslav@1890
  1984
            }
jaroslav@1890
  1985
            if (acquireQueued(node, savedState) || interrupted)
jaroslav@1890
  1986
                selfInterrupt();
jaroslav@1890
  1987
        }
jaroslav@1890
  1988
jaroslav@1890
  1989
        /*
jaroslav@1890
  1990
         * For interruptible waits, we need to track whether to throw
jaroslav@1890
  1991
         * InterruptedException, if interrupted while blocked on
jaroslav@1890
  1992
         * condition, versus reinterrupt current thread, if
jaroslav@1890
  1993
         * interrupted while blocked waiting to re-acquire.
jaroslav@1890
  1994
         */
jaroslav@1890
  1995
jaroslav@1890
  1996
        /** Mode meaning to reinterrupt on exit from wait */
jaroslav@1890
  1997
        private static final int REINTERRUPT =  1;
jaroslav@1890
  1998
        /** Mode meaning to throw InterruptedException on exit from wait */
jaroslav@1890
  1999
        private static final int THROW_IE    = -1;
jaroslav@1890
  2000
jaroslav@1890
  2001
        /**
jaroslav@1890
  2002
         * Checks for interrupt, returning THROW_IE if interrupted
jaroslav@1890
  2003
         * before signalled, REINTERRUPT if after signalled, or
jaroslav@1890
  2004
         * 0 if not interrupted.
jaroslav@1890
  2005
         */
jaroslav@1890
  2006
        private int checkInterruptWhileWaiting(Node node) {
jaroslav@1890
  2007
            return Thread.interrupted() ?
jaroslav@1890
  2008
                (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
jaroslav@1890
  2009
                0;
jaroslav@1890
  2010
        }
jaroslav@1890
  2011
jaroslav@1890
  2012
        /**
jaroslav@1890
  2013
         * Throws InterruptedException, reinterrupts current thread, or
jaroslav@1890
  2014
         * does nothing, depending on mode.
jaroslav@1890
  2015
         */
jaroslav@1890
  2016
        private void reportInterruptAfterWait(int interruptMode)
jaroslav@1890
  2017
            throws InterruptedException {
jaroslav@1890
  2018
            if (interruptMode == THROW_IE)
jaroslav@1890
  2019
                throw new InterruptedException();
jaroslav@1890
  2020
            else if (interruptMode == REINTERRUPT)
jaroslav@1890
  2021
                selfInterrupt();
jaroslav@1890
  2022
        }
jaroslav@1890
  2023
jaroslav@1890
  2024
        /**
jaroslav@1890
  2025
         * Implements interruptible condition wait.
jaroslav@1890
  2026
         * <ol>
jaroslav@1890
  2027
         * <li> If current thread is interrupted, throw InterruptedException.
jaroslav@1890
  2028
         * <li> Save lock state returned by {@link #getState}.
jaroslav@1890
  2029
         * <li> Invoke {@link #release} with
jaroslav@1890
  2030
         *      saved state as argument, throwing
jaroslav@1890
  2031
         *      IllegalMonitorStateException if it fails.
jaroslav@1890
  2032
         * <li> Block until signalled or interrupted.
jaroslav@1890
  2033
         * <li> Reacquire by invoking specialized version of
jaroslav@1890
  2034
         *      {@link #acquire} with saved state as argument.
jaroslav@1890
  2035
         * <li> If interrupted while blocked in step 4, throw InterruptedException.
jaroslav@1890
  2036
         * </ol>
jaroslav@1890
  2037
         */
jaroslav@1890
  2038
        public final void await() throws InterruptedException {
jaroslav@1890
  2039
            if (Thread.interrupted())
jaroslav@1890
  2040
                throw new InterruptedException();
jaroslav@1890
  2041
            Node node = addConditionWaiter();
jaroslav@1890
  2042
            int savedState = fullyRelease(node);
jaroslav@1890
  2043
            int interruptMode = 0;
jaroslav@1890
  2044
            while (!isOnSyncQueue(node)) {
jaroslav@1890
  2045
                LockSupport.park(this);
jaroslav@1890
  2046
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
jaroslav@1890
  2047
                    break;
jaroslav@1890
  2048
            }
jaroslav@1890
  2049
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
jaroslav@1890
  2050
                interruptMode = REINTERRUPT;
jaroslav@1890
  2051
            if (node.nextWaiter != null) // clean up if cancelled
jaroslav@1890
  2052
                unlinkCancelledWaiters();
jaroslav@1890
  2053
            if (interruptMode != 0)
jaroslav@1890
  2054
                reportInterruptAfterWait(interruptMode);
jaroslav@1890
  2055
        }
jaroslav@1890
  2056
jaroslav@1890
  2057
        /**
jaroslav@1890
  2058
         * Implements timed condition wait.
jaroslav@1890
  2059
         * <ol>
jaroslav@1890
  2060
         * <li> If current thread is interrupted, throw InterruptedException.
jaroslav@1890
  2061
         * <li> Save lock state returned by {@link #getState}.
jaroslav@1890
  2062
         * <li> Invoke {@link #release} with
jaroslav@1890
  2063
         *      saved state as argument, throwing
jaroslav@1890
  2064
         *      IllegalMonitorStateException if it fails.
jaroslav@1890
  2065
         * <li> Block until signalled, interrupted, or timed out.
jaroslav@1890
  2066
         * <li> Reacquire by invoking specialized version of
jaroslav@1890
  2067
         *      {@link #acquire} with saved state as argument.
jaroslav@1890
  2068
         * <li> If interrupted while blocked in step 4, throw InterruptedException.
jaroslav@1890
  2069
         * </ol>
jaroslav@1890
  2070
         */
jaroslav@1890
  2071
        public final long awaitNanos(long nanosTimeout)
jaroslav@1890
  2072
                throws InterruptedException {
jaroslav@1890
  2073
            if (Thread.interrupted())
jaroslav@1890
  2074
                throw new InterruptedException();
jaroslav@1890
  2075
            Node node = addConditionWaiter();
jaroslav@1890
  2076
            int savedState = fullyRelease(node);
jaroslav@1890
  2077
            long lastTime = System.nanoTime();
jaroslav@1890
  2078
            int interruptMode = 0;
jaroslav@1890
  2079
            while (!isOnSyncQueue(node)) {
jaroslav@1890
  2080
                if (nanosTimeout <= 0L) {
jaroslav@1890
  2081
                    transferAfterCancelledWait(node);
jaroslav@1890
  2082
                    break;
jaroslav@1890
  2083
                }
jaroslav@1890
  2084
                LockSupport.parkNanos(this, nanosTimeout);
jaroslav@1890
  2085
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
jaroslav@1890
  2086
                    break;
jaroslav@1890
  2087
jaroslav@1890
  2088
                long now = System.nanoTime();
jaroslav@1890
  2089
                nanosTimeout -= now - lastTime;
jaroslav@1890
  2090
                lastTime = now;
jaroslav@1890
  2091
            }
jaroslav@1890
  2092
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
jaroslav@1890
  2093
                interruptMode = REINTERRUPT;
jaroslav@1890
  2094
            if (node.nextWaiter != null)
jaroslav@1890
  2095
                unlinkCancelledWaiters();
jaroslav@1890
  2096
            if (interruptMode != 0)
jaroslav@1890
  2097
                reportInterruptAfterWait(interruptMode);
jaroslav@1890
  2098
            return nanosTimeout - (System.nanoTime() - lastTime);
jaroslav@1890
  2099
        }
jaroslav@1890
  2100
jaroslav@1890
  2101
        /**
jaroslav@1890
  2102
         * Implements absolute timed condition wait.
jaroslav@1890
  2103
         * <ol>
jaroslav@1890
  2104
         * <li> If current thread is interrupted, throw InterruptedException.
jaroslav@1890
  2105
         * <li> Save lock state returned by {@link #getState}.
jaroslav@1890
  2106
         * <li> Invoke {@link #release} with
jaroslav@1890
  2107
         *      saved state as argument, throwing
jaroslav@1890
  2108
         *      IllegalMonitorStateException if it fails.
jaroslav@1890
  2109
         * <li> Block until signalled, interrupted, or timed out.
jaroslav@1890
  2110
         * <li> Reacquire by invoking specialized version of
jaroslav@1890
  2111
         *      {@link #acquire} with saved state as argument.
jaroslav@1890
  2112
         * <li> If interrupted while blocked in step 4, throw InterruptedException.
jaroslav@1890
  2113
         * <li> If timed out while blocked in step 4, return false, else true.
jaroslav@1890
  2114
         * </ol>
jaroslav@1890
  2115
         */
jaroslav@1890
  2116
        public final boolean awaitUntil(Date deadline)
jaroslav@1890
  2117
                throws InterruptedException {
jaroslav@1890
  2118
            if (deadline == null)
jaroslav@1890
  2119
                throw new NullPointerException();
jaroslav@1890
  2120
            long abstime = deadline.getTime();
jaroslav@1890
  2121
            if (Thread.interrupted())
jaroslav@1890
  2122
                throw new InterruptedException();
jaroslav@1890
  2123
            Node node = addConditionWaiter();
jaroslav@1890
  2124
            int savedState = fullyRelease(node);
jaroslav@1890
  2125
            boolean timedout = false;
jaroslav@1890
  2126
            int interruptMode = 0;
jaroslav@1890
  2127
            while (!isOnSyncQueue(node)) {
jaroslav@1890
  2128
                if (System.currentTimeMillis() > abstime) {
jaroslav@1890
  2129
                    timedout = transferAfterCancelledWait(node);
jaroslav@1890
  2130
                    break;
jaroslav@1890
  2131
                }
jaroslav@1890
  2132
                LockSupport.parkUntil(this, abstime);
jaroslav@1890
  2133
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
jaroslav@1890
  2134
                    break;
jaroslav@1890
  2135
            }
jaroslav@1890
  2136
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
jaroslav@1890
  2137
                interruptMode = REINTERRUPT;
jaroslav@1890
  2138
            if (node.nextWaiter != null)
jaroslav@1890
  2139
                unlinkCancelledWaiters();
jaroslav@1890
  2140
            if (interruptMode != 0)
jaroslav@1890
  2141
                reportInterruptAfterWait(interruptMode);
jaroslav@1890
  2142
            return !timedout;
jaroslav@1890
  2143
        }
jaroslav@1890
  2144
jaroslav@1890
  2145
        /**
jaroslav@1890
  2146
         * Implements timed condition wait.
jaroslav@1890
  2147
         * <ol>
jaroslav@1890
  2148
         * <li> If current thread is interrupted, throw InterruptedException.
jaroslav@1890
  2149
         * <li> Save lock state returned by {@link #getState}.
jaroslav@1890
  2150
         * <li> Invoke {@link #release} with
jaroslav@1890
  2151
         *      saved state as argument, throwing
jaroslav@1890
  2152
         *      IllegalMonitorStateException if it fails.
jaroslav@1890
  2153
         * <li> Block until signalled, interrupted, or timed out.
jaroslav@1890
  2154
         * <li> Reacquire by invoking specialized version of
jaroslav@1890
  2155
         *      {@link #acquire} with saved state as argument.
jaroslav@1890
  2156
         * <li> If interrupted while blocked in step 4, throw InterruptedException.
jaroslav@1890
  2157
         * <li> If timed out while blocked in step 4, return false, else true.
jaroslav@1890
  2158
         * </ol>
jaroslav@1890
  2159
         */
jaroslav@1890
  2160
        public final boolean await(long time, TimeUnit unit)
jaroslav@1890
  2161
                throws InterruptedException {
jaroslav@1890
  2162
            if (unit == null)
jaroslav@1890
  2163
                throw new NullPointerException();
jaroslav@1890
  2164
            long nanosTimeout = unit.toNanos(time);
jaroslav@1890
  2165
            if (Thread.interrupted())
jaroslav@1890
  2166
                throw new InterruptedException();
jaroslav@1890
  2167
            Node node = addConditionWaiter();
jaroslav@1890
  2168
            int savedState = fullyRelease(node);
jaroslav@1890
  2169
            long lastTime = System.nanoTime();
jaroslav@1890
  2170
            boolean timedout = false;
jaroslav@1890
  2171
            int interruptMode = 0;
jaroslav@1890
  2172
            while (!isOnSyncQueue(node)) {
jaroslav@1890
  2173
                if (nanosTimeout <= 0L) {
jaroslav@1890
  2174
                    timedout = transferAfterCancelledWait(node);
jaroslav@1890
  2175
                    break;
jaroslav@1890
  2176
                }
jaroslav@1890
  2177
                if (nanosTimeout >= spinForTimeoutThreshold)
jaroslav@1890
  2178
                    LockSupport.parkNanos(this, nanosTimeout);
jaroslav@1890
  2179
                if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
jaroslav@1890
  2180
                    break;
jaroslav@1890
  2181
                long now = System.nanoTime();
jaroslav@1890
  2182
                nanosTimeout -= now - lastTime;
jaroslav@1890
  2183
                lastTime = now;
jaroslav@1890
  2184
            }
jaroslav@1890
  2185
            if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
jaroslav@1890
  2186
                interruptMode = REINTERRUPT;
jaroslav@1890
  2187
            if (node.nextWaiter != null)
jaroslav@1890
  2188
                unlinkCancelledWaiters();
jaroslav@1890
  2189
            if (interruptMode != 0)
jaroslav@1890
  2190
                reportInterruptAfterWait(interruptMode);
jaroslav@1890
  2191
            return !timedout;
jaroslav@1890
  2192
        }
jaroslav@1890
  2193
jaroslav@1890
  2194
        //  support for instrumentation
jaroslav@1890
  2195
jaroslav@1890
  2196
        /**
jaroslav@1890
  2197
         * Returns true if this condition was created by the given
jaroslav@1890
  2198
         * synchronization object.
jaroslav@1890
  2199
         *
jaroslav@1890
  2200
         * @return {@code true} if owned
jaroslav@1890
  2201
         */
jaroslav@1890
  2202
        final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
jaroslav@1890
  2203
            return sync == AbstractQueuedSynchronizer.this;
jaroslav@1890
  2204
        }
jaroslav@1890
  2205
jaroslav@1890
  2206
        /**
jaroslav@1890
  2207
         * Queries whether any threads are waiting on this condition.
jaroslav@1890
  2208
         * Implements {@link AbstractQueuedSynchronizer#hasWaiters}.
jaroslav@1890
  2209
         *
jaroslav@1890
  2210
         * @return {@code true} if there are any waiting threads
jaroslav@1890
  2211
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890
  2212
         *         returns {@code false}
jaroslav@1890
  2213
         */
jaroslav@1890
  2214
        protected final boolean hasWaiters() {
jaroslav@1890
  2215
            if (!isHeldExclusively())
jaroslav@1890
  2216
                throw new IllegalMonitorStateException();
jaroslav@1890
  2217
            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
jaroslav@1890
  2218
                if (w.waitStatus == Node.CONDITION)
jaroslav@1890
  2219
                    return true;
jaroslav@1890
  2220
            }
jaroslav@1890
  2221
            return false;
jaroslav@1890
  2222
        }
jaroslav@1890
  2223
jaroslav@1890
  2224
        /**
jaroslav@1890
  2225
         * Returns an estimate of the number of threads waiting on
jaroslav@1890
  2226
         * this condition.
jaroslav@1890
  2227
         * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength}.
jaroslav@1890
  2228
         *
jaroslav@1890
  2229
         * @return the estimated number of waiting threads
jaroslav@1890
  2230
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890
  2231
         *         returns {@code false}
jaroslav@1890
  2232
         */
jaroslav@1890
  2233
        protected final int getWaitQueueLength() {
jaroslav@1890
  2234
            if (!isHeldExclusively())
jaroslav@1890
  2235
                throw new IllegalMonitorStateException();
jaroslav@1890
  2236
            int n = 0;
jaroslav@1890
  2237
            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
jaroslav@1890
  2238
                if (w.waitStatus == Node.CONDITION)
jaroslav@1890
  2239
                    ++n;
jaroslav@1890
  2240
            }
jaroslav@1890
  2241
            return n;
jaroslav@1890
  2242
        }
jaroslav@1890
  2243
jaroslav@1890
  2244
        /**
jaroslav@1890
  2245
         * Returns a collection containing those threads that may be
jaroslav@1890
  2246
         * waiting on this Condition.
jaroslav@1890
  2247
         * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads}.
jaroslav@1890
  2248
         *
jaroslav@1890
  2249
         * @return the collection of threads
jaroslav@1890
  2250
         * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
jaroslav@1890
  2251
         *         returns {@code false}
jaroslav@1890
  2252
         */
jaroslav@1890
  2253
        protected final Collection<Thread> getWaitingThreads() {
jaroslav@1890
  2254
            if (!isHeldExclusively())
jaroslav@1890
  2255
                throw new IllegalMonitorStateException();
jaroslav@1890
  2256
            ArrayList<Thread> list = new ArrayList<Thread>();
jaroslav@1890
  2257
            for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
jaroslav@1890
  2258
                if (w.waitStatus == Node.CONDITION) {
jaroslav@1890
  2259
                    Thread t = w.thread;
jaroslav@1890
  2260
                    if (t != null)
jaroslav@1890
  2261
                        list.add(t);
jaroslav@1890
  2262
                }
jaroslav@1890
  2263
            }
jaroslav@1890
  2264
            return list;
jaroslav@1890
  2265
        }
jaroslav@1890
  2266
    }
jaroslav@1890
  2267
jaroslav@1890
  2268
    /**
jaroslav@1890
  2269
     * Setup to support compareAndSet. We need to natively implement
jaroslav@1890
  2270
     * this here: For the sake of permitting future enhancements, we
jaroslav@1890
  2271
     * cannot explicitly subclass AtomicInteger, which would be
jaroslav@1890
  2272
     * efficient and useful otherwise. So, as the lesser of evils, we
jaroslav@1890
  2273
     * natively implement using hotspot intrinsics API. And while we
jaroslav@1890
  2274
     * are at it, we do the same for other CASable fields (which could
jaroslav@1890
  2275
     * otherwise be done with atomic field updaters).
jaroslav@1890
  2276
     */
jaroslav@1890
  2277
jaroslav@1890
  2278
jaroslav@1890
  2279
    /**
jaroslav@1890
  2280
     * CAS head field. Used only by enq.
jaroslav@1890
  2281
     */
jaroslav@1890
  2282
    private final boolean compareAndSetHead(Node update) {
jaroslav@1894
  2283
        if (head == null) {
jaroslav@1894
  2284
            head = update;
jaroslav@1894
  2285
            return true;
jaroslav@1894
  2286
        }
jaroslav@1894
  2287
        return false;
jaroslav@1890
  2288
    }
jaroslav@1890
  2289
jaroslav@1890
  2290
    /**
jaroslav@1890
  2291
     * CAS tail field. Used only by enq.
jaroslav@1890
  2292
     */
jaroslav@1890
  2293
    private final boolean compareAndSetTail(Node expect, Node update) {
jaroslav@1894
  2294
        if (tail == null) {
jaroslav@1894
  2295
            tail = update;
jaroslav@1894
  2296
            return true;
jaroslav@1894
  2297
        }
jaroslav@1894
  2298
        return false;
jaroslav@1890
  2299
    }
jaroslav@1890
  2300
jaroslav@1890
  2301
    /**
jaroslav@1890
  2302
     * CAS waitStatus field of a node.
jaroslav@1890
  2303
     */
jaroslav@1890
  2304
    private static final boolean compareAndSetWaitStatus(Node node,
jaroslav@1890
  2305
                                                         int expect,
jaroslav@1890
  2306
                                                         int update) {
jaroslav@1894
  2307
        if (node.waitStatus == expect) {
jaroslav@1894
  2308
            node.waitStatus = update;
jaroslav@1894
  2309
            return true;
jaroslav@1894
  2310
        }
jaroslav@1894
  2311
        return false;
jaroslav@1890
  2312
    }
jaroslav@1890
  2313
jaroslav@1890
  2314
    /**
jaroslav@1890
  2315
     * CAS next field of a node.
jaroslav@1890
  2316
     */
jaroslav@1890
  2317
    private static final boolean compareAndSetNext(Node node,
jaroslav@1890
  2318
                                                   Node expect,
jaroslav@1890
  2319
                                                   Node update) {
jaroslav@1894
  2320
        if (node.next == expect) {
jaroslav@1894
  2321
            node.next = update;
jaroslav@1894
  2322
            return true;
jaroslav@1894
  2323
        }
jaroslav@1894
  2324
        return false;
jaroslav@1890
  2325
    }
jaroslav@1890
  2326
}