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