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