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