rt/emul/compact/src/main/java/java/util/concurrent/locks/ReentrantReadWriteLock.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 19 Mar 2016 10:46:31 +0100
branchjdk7-b147
changeset 1890 212417b74b72
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.concurrent.*;
jaroslav@1890
    38
import java.util.concurrent.atomic.*;
jaroslav@1890
    39
import java.util.*;
jaroslav@1890
    40
jaroslav@1890
    41
/**
jaroslav@1890
    42
 * An implementation of {@link ReadWriteLock} supporting similar
jaroslav@1890
    43
 * semantics to {@link ReentrantLock}.
jaroslav@1890
    44
 * <p>This class has the following properties:
jaroslav@1890
    45
 *
jaroslav@1890
    46
 * <ul>
jaroslav@1890
    47
 * <li><b>Acquisition order</b>
jaroslav@1890
    48
 *
jaroslav@1890
    49
 * <p> This class does not impose a reader or writer preference
jaroslav@1890
    50
 * ordering for lock access.  However, it does support an optional
jaroslav@1890
    51
 * <em>fairness</em> policy.
jaroslav@1890
    52
 *
jaroslav@1890
    53
 * <dl>
jaroslav@1890
    54
 * <dt><b><i>Non-fair mode (default)</i></b>
jaroslav@1890
    55
 * <dd>When constructed as non-fair (the default), the order of entry
jaroslav@1890
    56
 * to the read and write lock is unspecified, subject to reentrancy
jaroslav@1890
    57
 * constraints.  A nonfair lock that is continuously contended may
jaroslav@1890
    58
 * indefinitely postpone one or more reader or writer threads, but
jaroslav@1890
    59
 * will normally have higher throughput than a fair lock.
jaroslav@1890
    60
 * <p>
jaroslav@1890
    61
 *
jaroslav@1890
    62
 * <dt><b><i>Fair mode</i></b>
jaroslav@1890
    63
 * <dd> When constructed as fair, threads contend for entry using an
jaroslav@1890
    64
 * approximately arrival-order policy. When the currently held lock
jaroslav@1890
    65
 * is released either the longest-waiting single writer thread will
jaroslav@1890
    66
 * be assigned the write lock, or if there is a group of reader threads
jaroslav@1890
    67
 * waiting longer than all waiting writer threads, that group will be
jaroslav@1890
    68
 * assigned the read lock.
jaroslav@1890
    69
 *
jaroslav@1890
    70
 * <p>A thread that tries to acquire a fair read lock (non-reentrantly)
jaroslav@1890
    71
 * will block if either the write lock is held, or there is a waiting
jaroslav@1890
    72
 * writer thread. The thread will not acquire the read lock until
jaroslav@1890
    73
 * after the oldest currently waiting writer thread has acquired and
jaroslav@1890
    74
 * released the write lock. Of course, if a waiting writer abandons
jaroslav@1890
    75
 * its wait, leaving one or more reader threads as the longest waiters
jaroslav@1890
    76
 * in the queue with the write lock free, then those readers will be
jaroslav@1890
    77
 * assigned the read lock.
jaroslav@1890
    78
 *
jaroslav@1890
    79
 * <p>A thread that tries to acquire a fair write lock (non-reentrantly)
jaroslav@1890
    80
 * will block unless both the read lock and write lock are free (which
jaroslav@1890
    81
 * implies there are no waiting threads).  (Note that the non-blocking
jaroslav@1890
    82
 * {@link ReadLock#tryLock()} and {@link WriteLock#tryLock()} methods
jaroslav@1890
    83
 * do not honor this fair setting and will acquire the lock if it is
jaroslav@1890
    84
 * possible, regardless of waiting threads.)
jaroslav@1890
    85
 * <p>
jaroslav@1890
    86
 * </dl>
jaroslav@1890
    87
 *
jaroslav@1890
    88
 * <li><b>Reentrancy</b>
jaroslav@1890
    89
 *
jaroslav@1890
    90
 * <p>This lock allows both readers and writers to reacquire read or
jaroslav@1890
    91
 * write locks in the style of a {@link ReentrantLock}. Non-reentrant
jaroslav@1890
    92
 * readers are not allowed until all write locks held by the writing
jaroslav@1890
    93
 * thread have been released.
jaroslav@1890
    94
 *
jaroslav@1890
    95
 * <p>Additionally, a writer can acquire the read lock, but not
jaroslav@1890
    96
 * vice-versa.  Among other applications, reentrancy can be useful
jaroslav@1890
    97
 * when write locks are held during calls or callbacks to methods that
jaroslav@1890
    98
 * perform reads under read locks.  If a reader tries to acquire the
jaroslav@1890
    99
 * write lock it will never succeed.
jaroslav@1890
   100
 *
jaroslav@1890
   101
 * <li><b>Lock downgrading</b>
jaroslav@1890
   102
 * <p>Reentrancy also allows downgrading from the write lock to a read lock,
jaroslav@1890
   103
 * by acquiring the write lock, then the read lock and then releasing the
jaroslav@1890
   104
 * write lock. However, upgrading from a read lock to the write lock is
jaroslav@1890
   105
 * <b>not</b> possible.
jaroslav@1890
   106
 *
jaroslav@1890
   107
 * <li><b>Interruption of lock acquisition</b>
jaroslav@1890
   108
 * <p>The read lock and write lock both support interruption during lock
jaroslav@1890
   109
 * acquisition.
jaroslav@1890
   110
 *
jaroslav@1890
   111
 * <li><b>{@link Condition} support</b>
jaroslav@1890
   112
 * <p>The write lock provides a {@link Condition} implementation that
jaroslav@1890
   113
 * behaves in the same way, with respect to the write lock, as the
jaroslav@1890
   114
 * {@link Condition} implementation provided by
jaroslav@1890
   115
 * {@link ReentrantLock#newCondition} does for {@link ReentrantLock}.
jaroslav@1890
   116
 * This {@link Condition} can, of course, only be used with the write lock.
jaroslav@1890
   117
 *
jaroslav@1890
   118
 * <p>The read lock does not support a {@link Condition} and
jaroslav@1890
   119
 * {@code readLock().newCondition()} throws
jaroslav@1890
   120
 * {@code UnsupportedOperationException}.
jaroslav@1890
   121
 *
jaroslav@1890
   122
 * <li><b>Instrumentation</b>
jaroslav@1890
   123
 * <p>This class supports methods to determine whether locks
jaroslav@1890
   124
 * are held or contended. These methods are designed for monitoring
jaroslav@1890
   125
 * system state, not for synchronization control.
jaroslav@1890
   126
 * </ul>
jaroslav@1890
   127
 *
jaroslav@1890
   128
 * <p>Serialization of this class behaves in the same way as built-in
jaroslav@1890
   129
 * locks: a deserialized lock is in the unlocked state, regardless of
jaroslav@1890
   130
 * its state when serialized.
jaroslav@1890
   131
 *
jaroslav@1890
   132
 * <p><b>Sample usages</b>. Here is a code sketch showing how to perform
jaroslav@1890
   133
 * lock downgrading after updating a cache (exception handling is
jaroslav@1890
   134
 * particularly tricky when handling multiple locks in a non-nested
jaroslav@1890
   135
 * fashion):
jaroslav@1890
   136
 *
jaroslav@1890
   137
 * <pre> {@code
jaroslav@1890
   138
 * class CachedData {
jaroslav@1890
   139
 *   Object data;
jaroslav@1890
   140
 *   volatile boolean cacheValid;
jaroslav@1890
   141
 *   final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
jaroslav@1890
   142
 *
jaroslav@1890
   143
 *   void processCachedData() {
jaroslav@1890
   144
 *     rwl.readLock().lock();
jaroslav@1890
   145
 *     if (!cacheValid) {
jaroslav@1890
   146
 *        // Must release read lock before acquiring write lock
jaroslav@1890
   147
 *        rwl.readLock().unlock();
jaroslav@1890
   148
 *        rwl.writeLock().lock();
jaroslav@1890
   149
 *        try {
jaroslav@1890
   150
 *          // Recheck state because another thread might have
jaroslav@1890
   151
 *          // acquired write lock and changed state before we did.
jaroslav@1890
   152
 *          if (!cacheValid) {
jaroslav@1890
   153
 *            data = ...
jaroslav@1890
   154
 *            cacheValid = true;
jaroslav@1890
   155
 *          }
jaroslav@1890
   156
 *          // Downgrade by acquiring read lock before releasing write lock
jaroslav@1890
   157
 *          rwl.readLock().lock();
jaroslav@1890
   158
 *        } finally {
jaroslav@1890
   159
 *          rwl.writeLock().unlock(); // Unlock write, still hold read
jaroslav@1890
   160
 *        }
jaroslav@1890
   161
 *     }
jaroslav@1890
   162
 *
jaroslav@1890
   163
 *     try {
jaroslav@1890
   164
 *       use(data);
jaroslav@1890
   165
 *     } finally {
jaroslav@1890
   166
 *       rwl.readLock().unlock();
jaroslav@1890
   167
 *     }
jaroslav@1890
   168
 *   }
jaroslav@1890
   169
 * }}</pre>
jaroslav@1890
   170
 *
jaroslav@1890
   171
 * ReentrantReadWriteLocks can be used to improve concurrency in some
jaroslav@1890
   172
 * uses of some kinds of Collections. This is typically worthwhile
jaroslav@1890
   173
 * only when the collections are expected to be large, accessed by
jaroslav@1890
   174
 * more reader threads than writer threads, and entail operations with
jaroslav@1890
   175
 * overhead that outweighs synchronization overhead. For example, here
jaroslav@1890
   176
 * is a class using a TreeMap that is expected to be large and
jaroslav@1890
   177
 * concurrently accessed.
jaroslav@1890
   178
 *
jaroslav@1890
   179
 * <pre>{@code
jaroslav@1890
   180
 * class RWDictionary {
jaroslav@1890
   181
 *    private final Map<String, Data> m = new TreeMap<String, Data>();
jaroslav@1890
   182
 *    private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
jaroslav@1890
   183
 *    private final Lock r = rwl.readLock();
jaroslav@1890
   184
 *    private final Lock w = rwl.writeLock();
jaroslav@1890
   185
 *
jaroslav@1890
   186
 *    public Data get(String key) {
jaroslav@1890
   187
 *        r.lock();
jaroslav@1890
   188
 *        try { return m.get(key); }
jaroslav@1890
   189
 *        finally { r.unlock(); }
jaroslav@1890
   190
 *    }
jaroslav@1890
   191
 *    public String[] allKeys() {
jaroslav@1890
   192
 *        r.lock();
jaroslav@1890
   193
 *        try { return m.keySet().toArray(); }
jaroslav@1890
   194
 *        finally { r.unlock(); }
jaroslav@1890
   195
 *    }
jaroslav@1890
   196
 *    public Data put(String key, Data value) {
jaroslav@1890
   197
 *        w.lock();
jaroslav@1890
   198
 *        try { return m.put(key, value); }
jaroslav@1890
   199
 *        finally { w.unlock(); }
jaroslav@1890
   200
 *    }
jaroslav@1890
   201
 *    public void clear() {
jaroslav@1890
   202
 *        w.lock();
jaroslav@1890
   203
 *        try { m.clear(); }
jaroslav@1890
   204
 *        finally { w.unlock(); }
jaroslav@1890
   205
 *    }
jaroslav@1890
   206
 * }}</pre>
jaroslav@1890
   207
 *
jaroslav@1890
   208
 * <h3>Implementation Notes</h3>
jaroslav@1890
   209
 *
jaroslav@1890
   210
 * <p>This lock supports a maximum of 65535 recursive write locks
jaroslav@1890
   211
 * and 65535 read locks. Attempts to exceed these limits result in
jaroslav@1890
   212
 * {@link Error} throws from locking methods.
jaroslav@1890
   213
 *
jaroslav@1890
   214
 * @since 1.5
jaroslav@1890
   215
 * @author Doug Lea
jaroslav@1890
   216
 *
jaroslav@1890
   217
 */
jaroslav@1890
   218
public class ReentrantReadWriteLock
jaroslav@1890
   219
        implements ReadWriteLock, java.io.Serializable {
jaroslav@1890
   220
    private static final long serialVersionUID = -6992448646407690164L;
jaroslav@1890
   221
    /** Inner class providing readlock */
jaroslav@1890
   222
    private final ReentrantReadWriteLock.ReadLock readerLock;
jaroslav@1890
   223
    /** Inner class providing writelock */
jaroslav@1890
   224
    private final ReentrantReadWriteLock.WriteLock writerLock;
jaroslav@1890
   225
    /** Performs all synchronization mechanics */
jaroslav@1890
   226
    final Sync sync;
jaroslav@1890
   227
jaroslav@1890
   228
    /**
jaroslav@1890
   229
     * Creates a new {@code ReentrantReadWriteLock} with
jaroslav@1890
   230
     * default (nonfair) ordering properties.
jaroslav@1890
   231
     */
jaroslav@1890
   232
    public ReentrantReadWriteLock() {
jaroslav@1890
   233
        this(false);
jaroslav@1890
   234
    }
jaroslav@1890
   235
jaroslav@1890
   236
    /**
jaroslav@1890
   237
     * Creates a new {@code ReentrantReadWriteLock} with
jaroslav@1890
   238
     * the given fairness policy.
jaroslav@1890
   239
     *
jaroslav@1890
   240
     * @param fair {@code true} if this lock should use a fair ordering policy
jaroslav@1890
   241
     */
jaroslav@1890
   242
    public ReentrantReadWriteLock(boolean fair) {
jaroslav@1890
   243
        sync = fair ? new FairSync() : new NonfairSync();
jaroslav@1890
   244
        readerLock = new ReadLock(this);
jaroslav@1890
   245
        writerLock = new WriteLock(this);
jaroslav@1890
   246
    }
jaroslav@1890
   247
jaroslav@1890
   248
    public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
jaroslav@1890
   249
    public ReentrantReadWriteLock.ReadLock  readLock()  { return readerLock; }
jaroslav@1890
   250
jaroslav@1890
   251
    /**
jaroslav@1890
   252
     * Synchronization implementation for ReentrantReadWriteLock.
jaroslav@1890
   253
     * Subclassed into fair and nonfair versions.
jaroslav@1890
   254
     */
jaroslav@1890
   255
    abstract static class Sync extends AbstractQueuedSynchronizer {
jaroslav@1890
   256
        private static final long serialVersionUID = 6317671515068378041L;
jaroslav@1890
   257
jaroslav@1890
   258
        /*
jaroslav@1890
   259
         * Read vs write count extraction constants and functions.
jaroslav@1890
   260
         * Lock state is logically divided into two unsigned shorts:
jaroslav@1890
   261
         * The lower one representing the exclusive (writer) lock hold count,
jaroslav@1890
   262
         * and the upper the shared (reader) hold count.
jaroslav@1890
   263
         */
jaroslav@1890
   264
jaroslav@1890
   265
        static final int SHARED_SHIFT   = 16;
jaroslav@1890
   266
        static final int SHARED_UNIT    = (1 << SHARED_SHIFT);
jaroslav@1890
   267
        static final int MAX_COUNT      = (1 << SHARED_SHIFT) - 1;
jaroslav@1890
   268
        static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
jaroslav@1890
   269
jaroslav@1890
   270
        /** Returns the number of shared holds represented in count  */
jaroslav@1890
   271
        static int sharedCount(int c)    { return c >>> SHARED_SHIFT; }
jaroslav@1890
   272
        /** Returns the number of exclusive holds represented in count  */
jaroslav@1890
   273
        static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
jaroslav@1890
   274
jaroslav@1890
   275
        /**
jaroslav@1890
   276
         * A counter for per-thread read hold counts.
jaroslav@1890
   277
         * Maintained as a ThreadLocal; cached in cachedHoldCounter
jaroslav@1890
   278
         */
jaroslav@1890
   279
        static final class HoldCounter {
jaroslav@1890
   280
            int count = 0;
jaroslav@1890
   281
            // Use id, not reference, to avoid garbage retention
jaroslav@1890
   282
            final long tid = Thread.currentThread().getId();
jaroslav@1890
   283
        }
jaroslav@1890
   284
jaroslav@1890
   285
        /**
jaroslav@1890
   286
         * ThreadLocal subclass. Easiest to explicitly define for sake
jaroslav@1890
   287
         * of deserialization mechanics.
jaroslav@1890
   288
         */
jaroslav@1890
   289
        static final class ThreadLocalHoldCounter
jaroslav@1890
   290
            extends ThreadLocal<HoldCounter> {
jaroslav@1890
   291
            public HoldCounter initialValue() {
jaroslav@1890
   292
                return new HoldCounter();
jaroslav@1890
   293
            }
jaroslav@1890
   294
        }
jaroslav@1890
   295
jaroslav@1890
   296
        /**
jaroslav@1890
   297
         * The number of reentrant read locks held by current thread.
jaroslav@1890
   298
         * Initialized only in constructor and readObject.
jaroslav@1890
   299
         * Removed whenever a thread's read hold count drops to 0.
jaroslav@1890
   300
         */
jaroslav@1890
   301
        private transient ThreadLocalHoldCounter readHolds;
jaroslav@1890
   302
jaroslav@1890
   303
        /**
jaroslav@1890
   304
         * The hold count of the last thread to successfully acquire
jaroslav@1890
   305
         * readLock. This saves ThreadLocal lookup in the common case
jaroslav@1890
   306
         * where the next thread to release is the last one to
jaroslav@1890
   307
         * acquire. This is non-volatile since it is just used
jaroslav@1890
   308
         * as a heuristic, and would be great for threads to cache.
jaroslav@1890
   309
         *
jaroslav@1890
   310
         * <p>Can outlive the Thread for which it is caching the read
jaroslav@1890
   311
         * hold count, but avoids garbage retention by not retaining a
jaroslav@1890
   312
         * reference to the Thread.
jaroslav@1890
   313
         *
jaroslav@1890
   314
         * <p>Accessed via a benign data race; relies on the memory
jaroslav@1890
   315
         * model's final field and out-of-thin-air guarantees.
jaroslav@1890
   316
         */
jaroslav@1890
   317
        private transient HoldCounter cachedHoldCounter;
jaroslav@1890
   318
jaroslav@1890
   319
        /**
jaroslav@1890
   320
         * firstReader is the first thread to have acquired the read lock.
jaroslav@1890
   321
         * firstReaderHoldCount is firstReader's hold count.
jaroslav@1890
   322
         *
jaroslav@1890
   323
         * <p>More precisely, firstReader is the unique thread that last
jaroslav@1890
   324
         * changed the shared count from 0 to 1, and has not released the
jaroslav@1890
   325
         * read lock since then; null if there is no such thread.
jaroslav@1890
   326
         *
jaroslav@1890
   327
         * <p>Cannot cause garbage retention unless the thread terminated
jaroslav@1890
   328
         * without relinquishing its read locks, since tryReleaseShared
jaroslav@1890
   329
         * sets it to null.
jaroslav@1890
   330
         *
jaroslav@1890
   331
         * <p>Accessed via a benign data race; relies on the memory
jaroslav@1890
   332
         * model's out-of-thin-air guarantees for references.
jaroslav@1890
   333
         *
jaroslav@1890
   334
         * <p>This allows tracking of read holds for uncontended read
jaroslav@1890
   335
         * locks to be very cheap.
jaroslav@1890
   336
         */
jaroslav@1890
   337
        private transient Thread firstReader = null;
jaroslav@1890
   338
        private transient int firstReaderHoldCount;
jaroslav@1890
   339
jaroslav@1890
   340
        Sync() {
jaroslav@1890
   341
            readHolds = new ThreadLocalHoldCounter();
jaroslav@1890
   342
            setState(getState()); // ensures visibility of readHolds
jaroslav@1890
   343
        }
jaroslav@1890
   344
jaroslav@1890
   345
        /*
jaroslav@1890
   346
         * Acquires and releases use the same code for fair and
jaroslav@1890
   347
         * nonfair locks, but differ in whether/how they allow barging
jaroslav@1890
   348
         * when queues are non-empty.
jaroslav@1890
   349
         */
jaroslav@1890
   350
jaroslav@1890
   351
        /**
jaroslav@1890
   352
         * Returns true if the current thread, when trying to acquire
jaroslav@1890
   353
         * the read lock, and otherwise eligible to do so, should block
jaroslav@1890
   354
         * because of policy for overtaking other waiting threads.
jaroslav@1890
   355
         */
jaroslav@1890
   356
        abstract boolean readerShouldBlock();
jaroslav@1890
   357
jaroslav@1890
   358
        /**
jaroslav@1890
   359
         * Returns true if the current thread, when trying to acquire
jaroslav@1890
   360
         * the write lock, and otherwise eligible to do so, should block
jaroslav@1890
   361
         * because of policy for overtaking other waiting threads.
jaroslav@1890
   362
         */
jaroslav@1890
   363
        abstract boolean writerShouldBlock();
jaroslav@1890
   364
jaroslav@1890
   365
        /*
jaroslav@1890
   366
         * Note that tryRelease and tryAcquire can be called by
jaroslav@1890
   367
         * Conditions. So it is possible that their arguments contain
jaroslav@1890
   368
         * both read and write holds that are all released during a
jaroslav@1890
   369
         * condition wait and re-established in tryAcquire.
jaroslav@1890
   370
         */
jaroslav@1890
   371
jaroslav@1890
   372
        protected final boolean tryRelease(int releases) {
jaroslav@1890
   373
            if (!isHeldExclusively())
jaroslav@1890
   374
                throw new IllegalMonitorStateException();
jaroslav@1890
   375
            int nextc = getState() - releases;
jaroslav@1890
   376
            boolean free = exclusiveCount(nextc) == 0;
jaroslav@1890
   377
            if (free)
jaroslav@1890
   378
                setExclusiveOwnerThread(null);
jaroslav@1890
   379
            setState(nextc);
jaroslav@1890
   380
            return free;
jaroslav@1890
   381
        }
jaroslav@1890
   382
jaroslav@1890
   383
        protected final boolean tryAcquire(int acquires) {
jaroslav@1890
   384
            /*
jaroslav@1890
   385
             * Walkthrough:
jaroslav@1890
   386
             * 1. If read count nonzero or write count nonzero
jaroslav@1890
   387
             *    and owner is a different thread, fail.
jaroslav@1890
   388
             * 2. If count would saturate, fail. (This can only
jaroslav@1890
   389
             *    happen if count is already nonzero.)
jaroslav@1890
   390
             * 3. Otherwise, this thread is eligible for lock if
jaroslav@1890
   391
             *    it is either a reentrant acquire or
jaroslav@1890
   392
             *    queue policy allows it. If so, update state
jaroslav@1890
   393
             *    and set owner.
jaroslav@1890
   394
             */
jaroslav@1890
   395
            Thread current = Thread.currentThread();
jaroslav@1890
   396
            int c = getState();
jaroslav@1890
   397
            int w = exclusiveCount(c);
jaroslav@1890
   398
            if (c != 0) {
jaroslav@1890
   399
                // (Note: if c != 0 and w == 0 then shared count != 0)
jaroslav@1890
   400
                if (w == 0 || current != getExclusiveOwnerThread())
jaroslav@1890
   401
                    return false;
jaroslav@1890
   402
                if (w + exclusiveCount(acquires) > MAX_COUNT)
jaroslav@1890
   403
                    throw new Error("Maximum lock count exceeded");
jaroslav@1890
   404
                // Reentrant acquire
jaroslav@1890
   405
                setState(c + acquires);
jaroslav@1890
   406
                return true;
jaroslav@1890
   407
            }
jaroslav@1890
   408
            if (writerShouldBlock() ||
jaroslav@1890
   409
                !compareAndSetState(c, c + acquires))
jaroslav@1890
   410
                return false;
jaroslav@1890
   411
            setExclusiveOwnerThread(current);
jaroslav@1890
   412
            return true;
jaroslav@1890
   413
        }
jaroslav@1890
   414
jaroslav@1890
   415
        protected final boolean tryReleaseShared(int unused) {
jaroslav@1890
   416
            Thread current = Thread.currentThread();
jaroslav@1890
   417
            if (firstReader == current) {
jaroslav@1890
   418
                // assert firstReaderHoldCount > 0;
jaroslav@1890
   419
                if (firstReaderHoldCount == 1)
jaroslav@1890
   420
                    firstReader = null;
jaroslav@1890
   421
                else
jaroslav@1890
   422
                    firstReaderHoldCount--;
jaroslav@1890
   423
            } else {
jaroslav@1890
   424
                HoldCounter rh = cachedHoldCounter;
jaroslav@1890
   425
                if (rh == null || rh.tid != current.getId())
jaroslav@1890
   426
                    rh = readHolds.get();
jaroslav@1890
   427
                int count = rh.count;
jaroslav@1890
   428
                if (count <= 1) {
jaroslav@1890
   429
                    readHolds.remove();
jaroslav@1890
   430
                    if (count <= 0)
jaroslav@1890
   431
                        throw unmatchedUnlockException();
jaroslav@1890
   432
                }
jaroslav@1890
   433
                --rh.count;
jaroslav@1890
   434
            }
jaroslav@1890
   435
            for (;;) {
jaroslav@1890
   436
                int c = getState();
jaroslav@1890
   437
                int nextc = c - SHARED_UNIT;
jaroslav@1890
   438
                if (compareAndSetState(c, nextc))
jaroslav@1890
   439
                    // Releasing the read lock has no effect on readers,
jaroslav@1890
   440
                    // but it may allow waiting writers to proceed if
jaroslav@1890
   441
                    // both read and write locks are now free.
jaroslav@1890
   442
                    return nextc == 0;
jaroslav@1890
   443
            }
jaroslav@1890
   444
        }
jaroslav@1890
   445
jaroslav@1890
   446
        private IllegalMonitorStateException unmatchedUnlockException() {
jaroslav@1890
   447
            return new IllegalMonitorStateException(
jaroslav@1890
   448
                "attempt to unlock read lock, not locked by current thread");
jaroslav@1890
   449
        }
jaroslav@1890
   450
jaroslav@1890
   451
        protected final int tryAcquireShared(int unused) {
jaroslav@1890
   452
            /*
jaroslav@1890
   453
             * Walkthrough:
jaroslav@1890
   454
             * 1. If write lock held by another thread, fail.
jaroslav@1890
   455
             * 2. Otherwise, this thread is eligible for
jaroslav@1890
   456
             *    lock wrt state, so ask if it should block
jaroslav@1890
   457
             *    because of queue policy. If not, try
jaroslav@1890
   458
             *    to grant by CASing state and updating count.
jaroslav@1890
   459
             *    Note that step does not check for reentrant
jaroslav@1890
   460
             *    acquires, which is postponed to full version
jaroslav@1890
   461
             *    to avoid having to check hold count in
jaroslav@1890
   462
             *    the more typical non-reentrant case.
jaroslav@1890
   463
             * 3. If step 2 fails either because thread
jaroslav@1890
   464
             *    apparently not eligible or CAS fails or count
jaroslav@1890
   465
             *    saturated, chain to version with full retry loop.
jaroslav@1890
   466
             */
jaroslav@1890
   467
            Thread current = Thread.currentThread();
jaroslav@1890
   468
            int c = getState();
jaroslav@1890
   469
            if (exclusiveCount(c) != 0 &&
jaroslav@1890
   470
                getExclusiveOwnerThread() != current)
jaroslav@1890
   471
                return -1;
jaroslav@1890
   472
            int r = sharedCount(c);
jaroslav@1890
   473
            if (!readerShouldBlock() &&
jaroslav@1890
   474
                r < MAX_COUNT &&
jaroslav@1890
   475
                compareAndSetState(c, c + SHARED_UNIT)) {
jaroslav@1890
   476
                if (r == 0) {
jaroslav@1890
   477
                    firstReader = current;
jaroslav@1890
   478
                    firstReaderHoldCount = 1;
jaroslav@1890
   479
                } else if (firstReader == current) {
jaroslav@1890
   480
                    firstReaderHoldCount++;
jaroslav@1890
   481
                } else {
jaroslav@1890
   482
                    HoldCounter rh = cachedHoldCounter;
jaroslav@1890
   483
                    if (rh == null || rh.tid != current.getId())
jaroslav@1890
   484
                        cachedHoldCounter = rh = readHolds.get();
jaroslav@1890
   485
                    else if (rh.count == 0)
jaroslav@1890
   486
                        readHolds.set(rh);
jaroslav@1890
   487
                    rh.count++;
jaroslav@1890
   488
                }
jaroslav@1890
   489
                return 1;
jaroslav@1890
   490
            }
jaroslav@1890
   491
            return fullTryAcquireShared(current);
jaroslav@1890
   492
        }
jaroslav@1890
   493
jaroslav@1890
   494
        /**
jaroslav@1890
   495
         * Full version of acquire for reads, that handles CAS misses
jaroslav@1890
   496
         * and reentrant reads not dealt with in tryAcquireShared.
jaroslav@1890
   497
         */
jaroslav@1890
   498
        final int fullTryAcquireShared(Thread current) {
jaroslav@1890
   499
            /*
jaroslav@1890
   500
             * This code is in part redundant with that in
jaroslav@1890
   501
             * tryAcquireShared but is simpler overall by not
jaroslav@1890
   502
             * complicating tryAcquireShared with interactions between
jaroslav@1890
   503
             * retries and lazily reading hold counts.
jaroslav@1890
   504
             */
jaroslav@1890
   505
            HoldCounter rh = null;
jaroslav@1890
   506
            for (;;) {
jaroslav@1890
   507
                int c = getState();
jaroslav@1890
   508
                if (exclusiveCount(c) != 0) {
jaroslav@1890
   509
                    if (getExclusiveOwnerThread() != current)
jaroslav@1890
   510
                        return -1;
jaroslav@1890
   511
                    // else we hold the exclusive lock; blocking here
jaroslav@1890
   512
                    // would cause deadlock.
jaroslav@1890
   513
                } else if (readerShouldBlock()) {
jaroslav@1890
   514
                    // Make sure we're not acquiring read lock reentrantly
jaroslav@1890
   515
                    if (firstReader == current) {
jaroslav@1890
   516
                        // assert firstReaderHoldCount > 0;
jaroslav@1890
   517
                    } else {
jaroslav@1890
   518
                        if (rh == null) {
jaroslav@1890
   519
                            rh = cachedHoldCounter;
jaroslav@1890
   520
                            if (rh == null || rh.tid != current.getId()) {
jaroslav@1890
   521
                                rh = readHolds.get();
jaroslav@1890
   522
                                if (rh.count == 0)
jaroslav@1890
   523
                                    readHolds.remove();
jaroslav@1890
   524
                            }
jaroslav@1890
   525
                        }
jaroslav@1890
   526
                        if (rh.count == 0)
jaroslav@1890
   527
                            return -1;
jaroslav@1890
   528
                    }
jaroslav@1890
   529
                }
jaroslav@1890
   530
                if (sharedCount(c) == MAX_COUNT)
jaroslav@1890
   531
                    throw new Error("Maximum lock count exceeded");
jaroslav@1890
   532
                if (compareAndSetState(c, c + SHARED_UNIT)) {
jaroslav@1890
   533
                    if (sharedCount(c) == 0) {
jaroslav@1890
   534
                        firstReader = current;
jaroslav@1890
   535
                        firstReaderHoldCount = 1;
jaroslav@1890
   536
                    } else if (firstReader == current) {
jaroslav@1890
   537
                        firstReaderHoldCount++;
jaroslav@1890
   538
                    } else {
jaroslav@1890
   539
                        if (rh == null)
jaroslav@1890
   540
                            rh = cachedHoldCounter;
jaroslav@1890
   541
                        if (rh == null || rh.tid != current.getId())
jaroslav@1890
   542
                            rh = readHolds.get();
jaroslav@1890
   543
                        else if (rh.count == 0)
jaroslav@1890
   544
                            readHolds.set(rh);
jaroslav@1890
   545
                        rh.count++;
jaroslav@1890
   546
                        cachedHoldCounter = rh; // cache for release
jaroslav@1890
   547
                    }
jaroslav@1890
   548
                    return 1;
jaroslav@1890
   549
                }
jaroslav@1890
   550
            }
jaroslav@1890
   551
        }
jaroslav@1890
   552
jaroslav@1890
   553
        /**
jaroslav@1890
   554
         * Performs tryLock for write, enabling barging in both modes.
jaroslav@1890
   555
         * This is identical in effect to tryAcquire except for lack
jaroslav@1890
   556
         * of calls to writerShouldBlock.
jaroslav@1890
   557
         */
jaroslav@1890
   558
        final boolean tryWriteLock() {
jaroslav@1890
   559
            Thread current = Thread.currentThread();
jaroslav@1890
   560
            int c = getState();
jaroslav@1890
   561
            if (c != 0) {
jaroslav@1890
   562
                int w = exclusiveCount(c);
jaroslav@1890
   563
                if (w == 0 || current != getExclusiveOwnerThread())
jaroslav@1890
   564
                    return false;
jaroslav@1890
   565
                if (w == MAX_COUNT)
jaroslav@1890
   566
                    throw new Error("Maximum lock count exceeded");
jaroslav@1890
   567
            }
jaroslav@1890
   568
            if (!compareAndSetState(c, c + 1))
jaroslav@1890
   569
                return false;
jaroslav@1890
   570
            setExclusiveOwnerThread(current);
jaroslav@1890
   571
            return true;
jaroslav@1890
   572
        }
jaroslav@1890
   573
jaroslav@1890
   574
        /**
jaroslav@1890
   575
         * Performs tryLock for read, enabling barging in both modes.
jaroslav@1890
   576
         * This is identical in effect to tryAcquireShared except for
jaroslav@1890
   577
         * lack of calls to readerShouldBlock.
jaroslav@1890
   578
         */
jaroslav@1890
   579
        final boolean tryReadLock() {
jaroslav@1890
   580
            Thread current = Thread.currentThread();
jaroslav@1890
   581
            for (;;) {
jaroslav@1890
   582
                int c = getState();
jaroslav@1890
   583
                if (exclusiveCount(c) != 0 &&
jaroslav@1890
   584
                    getExclusiveOwnerThread() != current)
jaroslav@1890
   585
                    return false;
jaroslav@1890
   586
                int r = sharedCount(c);
jaroslav@1890
   587
                if (r == MAX_COUNT)
jaroslav@1890
   588
                    throw new Error("Maximum lock count exceeded");
jaroslav@1890
   589
                if (compareAndSetState(c, c + SHARED_UNIT)) {
jaroslav@1890
   590
                    if (r == 0) {
jaroslav@1890
   591
                        firstReader = current;
jaroslav@1890
   592
                        firstReaderHoldCount = 1;
jaroslav@1890
   593
                    } else if (firstReader == current) {
jaroslav@1890
   594
                        firstReaderHoldCount++;
jaroslav@1890
   595
                    } else {
jaroslav@1890
   596
                        HoldCounter rh = cachedHoldCounter;
jaroslav@1890
   597
                        if (rh == null || rh.tid != current.getId())
jaroslav@1890
   598
                            cachedHoldCounter = rh = readHolds.get();
jaroslav@1890
   599
                        else if (rh.count == 0)
jaroslav@1890
   600
                            readHolds.set(rh);
jaroslav@1890
   601
                        rh.count++;
jaroslav@1890
   602
                    }
jaroslav@1890
   603
                    return true;
jaroslav@1890
   604
                }
jaroslav@1890
   605
            }
jaroslav@1890
   606
        }
jaroslav@1890
   607
jaroslav@1890
   608
        protected final boolean isHeldExclusively() {
jaroslav@1890
   609
            // While we must in general read state before owner,
jaroslav@1890
   610
            // we don't need to do so to check if current thread is owner
jaroslav@1890
   611
            return getExclusiveOwnerThread() == Thread.currentThread();
jaroslav@1890
   612
        }
jaroslav@1890
   613
jaroslav@1890
   614
        // Methods relayed to outer class
jaroslav@1890
   615
jaroslav@1890
   616
        final ConditionObject newCondition() {
jaroslav@1890
   617
            return new ConditionObject();
jaroslav@1890
   618
        }
jaroslav@1890
   619
jaroslav@1890
   620
        final Thread getOwner() {
jaroslav@1890
   621
            // Must read state before owner to ensure memory consistency
jaroslav@1890
   622
            return ((exclusiveCount(getState()) == 0) ?
jaroslav@1890
   623
                    null :
jaroslav@1890
   624
                    getExclusiveOwnerThread());
jaroslav@1890
   625
        }
jaroslav@1890
   626
jaroslav@1890
   627
        final int getReadLockCount() {
jaroslav@1890
   628
            return sharedCount(getState());
jaroslav@1890
   629
        }
jaroslav@1890
   630
jaroslav@1890
   631
        final boolean isWriteLocked() {
jaroslav@1890
   632
            return exclusiveCount(getState()) != 0;
jaroslav@1890
   633
        }
jaroslav@1890
   634
jaroslav@1890
   635
        final int getWriteHoldCount() {
jaroslav@1890
   636
            return isHeldExclusively() ? exclusiveCount(getState()) : 0;
jaroslav@1890
   637
        }
jaroslav@1890
   638
jaroslav@1890
   639
        final int getReadHoldCount() {
jaroslav@1890
   640
            if (getReadLockCount() == 0)
jaroslav@1890
   641
                return 0;
jaroslav@1890
   642
jaroslav@1890
   643
            Thread current = Thread.currentThread();
jaroslav@1890
   644
            if (firstReader == current)
jaroslav@1890
   645
                return firstReaderHoldCount;
jaroslav@1890
   646
jaroslav@1890
   647
            HoldCounter rh = cachedHoldCounter;
jaroslav@1890
   648
            if (rh != null && rh.tid == current.getId())
jaroslav@1890
   649
                return rh.count;
jaroslav@1890
   650
jaroslav@1890
   651
            int count = readHolds.get().count;
jaroslav@1890
   652
            if (count == 0) readHolds.remove();
jaroslav@1890
   653
            return count;
jaroslav@1890
   654
        }
jaroslav@1890
   655
jaroslav@1890
   656
        /**
jaroslav@1890
   657
         * Reconstitute this lock instance from a stream
jaroslav@1890
   658
         * @param s the stream
jaroslav@1890
   659
         */
jaroslav@1890
   660
        private void readObject(java.io.ObjectInputStream s)
jaroslav@1890
   661
            throws java.io.IOException, ClassNotFoundException {
jaroslav@1890
   662
            s.defaultReadObject();
jaroslav@1890
   663
            readHolds = new ThreadLocalHoldCounter();
jaroslav@1890
   664
            setState(0); // reset to unlocked state
jaroslav@1890
   665
        }
jaroslav@1890
   666
jaroslav@1890
   667
        final int getCount() { return getState(); }
jaroslav@1890
   668
    }
jaroslav@1890
   669
jaroslav@1890
   670
    /**
jaroslav@1890
   671
     * Nonfair version of Sync
jaroslav@1890
   672
     */
jaroslav@1890
   673
    static final class NonfairSync extends Sync {
jaroslav@1890
   674
        private static final long serialVersionUID = -8159625535654395037L;
jaroslav@1890
   675
        final boolean writerShouldBlock() {
jaroslav@1890
   676
            return false; // writers can always barge
jaroslav@1890
   677
        }
jaroslav@1890
   678
        final boolean readerShouldBlock() {
jaroslav@1890
   679
            /* As a heuristic to avoid indefinite writer starvation,
jaroslav@1890
   680
             * block if the thread that momentarily appears to be head
jaroslav@1890
   681
             * of queue, if one exists, is a waiting writer.  This is
jaroslav@1890
   682
             * only a probabilistic effect since a new reader will not
jaroslav@1890
   683
             * block if there is a waiting writer behind other enabled
jaroslav@1890
   684
             * readers that have not yet drained from the queue.
jaroslav@1890
   685
             */
jaroslav@1890
   686
            return apparentlyFirstQueuedIsExclusive();
jaroslav@1890
   687
        }
jaroslav@1890
   688
    }
jaroslav@1890
   689
jaroslav@1890
   690
    /**
jaroslav@1890
   691
     * Fair version of Sync
jaroslav@1890
   692
     */
jaroslav@1890
   693
    static final class FairSync extends Sync {
jaroslav@1890
   694
        private static final long serialVersionUID = -2274990926593161451L;
jaroslav@1890
   695
        final boolean writerShouldBlock() {
jaroslav@1890
   696
            return hasQueuedPredecessors();
jaroslav@1890
   697
        }
jaroslav@1890
   698
        final boolean readerShouldBlock() {
jaroslav@1890
   699
            return hasQueuedPredecessors();
jaroslav@1890
   700
        }
jaroslav@1890
   701
    }
jaroslav@1890
   702
jaroslav@1890
   703
    /**
jaroslav@1890
   704
     * The lock returned by method {@link ReentrantReadWriteLock#readLock}.
jaroslav@1890
   705
     */
jaroslav@1890
   706
    public static class ReadLock implements Lock, java.io.Serializable {
jaroslav@1890
   707
        private static final long serialVersionUID = -5992448646407690164L;
jaroslav@1890
   708
        private final Sync sync;
jaroslav@1890
   709
jaroslav@1890
   710
        /**
jaroslav@1890
   711
         * Constructor for use by subclasses
jaroslav@1890
   712
         *
jaroslav@1890
   713
         * @param lock the outer lock object
jaroslav@1890
   714
         * @throws NullPointerException if the lock is null
jaroslav@1890
   715
         */
jaroslav@1890
   716
        protected ReadLock(ReentrantReadWriteLock lock) {
jaroslav@1890
   717
            sync = lock.sync;
jaroslav@1890
   718
        }
jaroslav@1890
   719
jaroslav@1890
   720
        /**
jaroslav@1890
   721
         * Acquires the read lock.
jaroslav@1890
   722
         *
jaroslav@1890
   723
         * <p>Acquires the read lock if the write lock is not held by
jaroslav@1890
   724
         * another thread and returns immediately.
jaroslav@1890
   725
         *
jaroslav@1890
   726
         * <p>If the write lock is held by another thread then
jaroslav@1890
   727
         * the current thread becomes disabled for thread scheduling
jaroslav@1890
   728
         * purposes and lies dormant until the read lock has been acquired.
jaroslav@1890
   729
         */
jaroslav@1890
   730
        public void lock() {
jaroslav@1890
   731
            sync.acquireShared(1);
jaroslav@1890
   732
        }
jaroslav@1890
   733
jaroslav@1890
   734
        /**
jaroslav@1890
   735
         * Acquires the read lock unless the current thread is
jaroslav@1890
   736
         * {@linkplain Thread#interrupt interrupted}.
jaroslav@1890
   737
         *
jaroslav@1890
   738
         * <p>Acquires the read lock if the write lock is not held
jaroslav@1890
   739
         * by another thread and returns immediately.
jaroslav@1890
   740
         *
jaroslav@1890
   741
         * <p>If the write lock is held by another thread then the
jaroslav@1890
   742
         * current thread becomes disabled for thread scheduling
jaroslav@1890
   743
         * purposes and lies dormant until one of two things happens:
jaroslav@1890
   744
         *
jaroslav@1890
   745
         * <ul>
jaroslav@1890
   746
         *
jaroslav@1890
   747
         * <li>The read lock is acquired by the current thread; or
jaroslav@1890
   748
         *
jaroslav@1890
   749
         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
jaroslav@1890
   750
         * the current thread.
jaroslav@1890
   751
         *
jaroslav@1890
   752
         * </ul>
jaroslav@1890
   753
         *
jaroslav@1890
   754
         * <p>If the current thread:
jaroslav@1890
   755
         *
jaroslav@1890
   756
         * <ul>
jaroslav@1890
   757
         *
jaroslav@1890
   758
         * <li>has its interrupted status set on entry to this method; or
jaroslav@1890
   759
         *
jaroslav@1890
   760
         * <li>is {@linkplain Thread#interrupt interrupted} while
jaroslav@1890
   761
         * acquiring the read lock,
jaroslav@1890
   762
         *
jaroslav@1890
   763
         * </ul>
jaroslav@1890
   764
         *
jaroslav@1890
   765
         * then {@link InterruptedException} is thrown and the current
jaroslav@1890
   766
         * thread's interrupted status is cleared.
jaroslav@1890
   767
         *
jaroslav@1890
   768
         * <p>In this implementation, as this method is an explicit
jaroslav@1890
   769
         * interruption point, preference is given to responding to
jaroslav@1890
   770
         * the interrupt over normal or reentrant acquisition of the
jaroslav@1890
   771
         * lock.
jaroslav@1890
   772
         *
jaroslav@1890
   773
         * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
   774
         */
jaroslav@1890
   775
        public void lockInterruptibly() throws InterruptedException {
jaroslav@1890
   776
            sync.acquireSharedInterruptibly(1);
jaroslav@1890
   777
        }
jaroslav@1890
   778
jaroslav@1890
   779
        /**
jaroslav@1890
   780
         * Acquires the read lock only if the write lock is not held by
jaroslav@1890
   781
         * another thread at the time of invocation.
jaroslav@1890
   782
         *
jaroslav@1890
   783
         * <p>Acquires the read lock if the write lock is not held by
jaroslav@1890
   784
         * another thread and returns immediately with the value
jaroslav@1890
   785
         * {@code true}. Even when this lock has been set to use a
jaroslav@1890
   786
         * fair ordering policy, a call to {@code tryLock()}
jaroslav@1890
   787
         * <em>will</em> immediately acquire the read lock if it is
jaroslav@1890
   788
         * available, whether or not other threads are currently
jaroslav@1890
   789
         * waiting for the read lock.  This &quot;barging&quot; behavior
jaroslav@1890
   790
         * can be useful in certain circumstances, even though it
jaroslav@1890
   791
         * breaks fairness. If you want to honor the fairness setting
jaroslav@1890
   792
         * for this lock, then use {@link #tryLock(long, TimeUnit)
jaroslav@1890
   793
         * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent
jaroslav@1890
   794
         * (it also detects interruption).
jaroslav@1890
   795
         *
jaroslav@1890
   796
         * <p>If the write lock is held by another thread then
jaroslav@1890
   797
         * this method will return immediately with the value
jaroslav@1890
   798
         * {@code false}.
jaroslav@1890
   799
         *
jaroslav@1890
   800
         * @return {@code true} if the read lock was acquired
jaroslav@1890
   801
         */
jaroslav@1890
   802
        public  boolean tryLock() {
jaroslav@1890
   803
            return sync.tryReadLock();
jaroslav@1890
   804
        }
jaroslav@1890
   805
jaroslav@1890
   806
        /**
jaroslav@1890
   807
         * Acquires the read lock if the write lock is not held by
jaroslav@1890
   808
         * another thread within the given waiting time and the
jaroslav@1890
   809
         * current thread has not been {@linkplain Thread#interrupt
jaroslav@1890
   810
         * interrupted}.
jaroslav@1890
   811
         *
jaroslav@1890
   812
         * <p>Acquires the read lock if the write lock is not held by
jaroslav@1890
   813
         * another thread and returns immediately with the value
jaroslav@1890
   814
         * {@code true}. If this lock has been set to use a fair
jaroslav@1890
   815
         * ordering policy then an available lock <em>will not</em> be
jaroslav@1890
   816
         * acquired if any other threads are waiting for the
jaroslav@1890
   817
         * lock. This is in contrast to the {@link #tryLock()}
jaroslav@1890
   818
         * method. If you want a timed {@code tryLock} that does
jaroslav@1890
   819
         * permit barging on a fair lock then combine the timed and
jaroslav@1890
   820
         * un-timed forms together:
jaroslav@1890
   821
         *
jaroslav@1890
   822
         * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
jaroslav@1890
   823
         * </pre>
jaroslav@1890
   824
         *
jaroslav@1890
   825
         * <p>If the write lock is held by another thread then the
jaroslav@1890
   826
         * current thread becomes disabled for thread scheduling
jaroslav@1890
   827
         * purposes and lies dormant until one of three things happens:
jaroslav@1890
   828
         *
jaroslav@1890
   829
         * <ul>
jaroslav@1890
   830
         *
jaroslav@1890
   831
         * <li>The read lock is acquired by the current thread; or
jaroslav@1890
   832
         *
jaroslav@1890
   833
         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
jaroslav@1890
   834
         * the current thread; or
jaroslav@1890
   835
         *
jaroslav@1890
   836
         * <li>The specified waiting time elapses.
jaroslav@1890
   837
         *
jaroslav@1890
   838
         * </ul>
jaroslav@1890
   839
         *
jaroslav@1890
   840
         * <p>If the read lock is acquired then the value {@code true} is
jaroslav@1890
   841
         * returned.
jaroslav@1890
   842
         *
jaroslav@1890
   843
         * <p>If the current thread:
jaroslav@1890
   844
         *
jaroslav@1890
   845
         * <ul>
jaroslav@1890
   846
         *
jaroslav@1890
   847
         * <li>has its interrupted status set on entry to this method; or
jaroslav@1890
   848
         *
jaroslav@1890
   849
         * <li>is {@linkplain Thread#interrupt interrupted} while
jaroslav@1890
   850
         * acquiring the read lock,
jaroslav@1890
   851
         *
jaroslav@1890
   852
         * </ul> then {@link InterruptedException} is thrown and the
jaroslav@1890
   853
         * current thread's interrupted status is cleared.
jaroslav@1890
   854
         *
jaroslav@1890
   855
         * <p>If the specified waiting time elapses then the value
jaroslav@1890
   856
         * {@code false} is returned.  If the time is less than or
jaroslav@1890
   857
         * equal to zero, the method will not wait at all.
jaroslav@1890
   858
         *
jaroslav@1890
   859
         * <p>In this implementation, as this method is an explicit
jaroslav@1890
   860
         * interruption point, preference is given to responding to
jaroslav@1890
   861
         * the interrupt over normal or reentrant acquisition of the
jaroslav@1890
   862
         * lock, and over reporting the elapse of the waiting time.
jaroslav@1890
   863
         *
jaroslav@1890
   864
         * @param timeout the time to wait for the read lock
jaroslav@1890
   865
         * @param unit the time unit of the timeout argument
jaroslav@1890
   866
         * @return {@code true} if the read lock was acquired
jaroslav@1890
   867
         * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
   868
         * @throws NullPointerException if the time unit is null
jaroslav@1890
   869
         *
jaroslav@1890
   870
         */
jaroslav@1890
   871
        public boolean tryLock(long timeout, TimeUnit unit)
jaroslav@1890
   872
                throws InterruptedException {
jaroslav@1890
   873
            return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
jaroslav@1890
   874
        }
jaroslav@1890
   875
jaroslav@1890
   876
        /**
jaroslav@1890
   877
         * Attempts to release this lock.
jaroslav@1890
   878
         *
jaroslav@1890
   879
         * <p> If the number of readers is now zero then the lock
jaroslav@1890
   880
         * is made available for write lock attempts.
jaroslav@1890
   881
         */
jaroslav@1890
   882
        public  void unlock() {
jaroslav@1890
   883
            sync.releaseShared(1);
jaroslav@1890
   884
        }
jaroslav@1890
   885
jaroslav@1890
   886
        /**
jaroslav@1890
   887
         * Throws {@code UnsupportedOperationException} because
jaroslav@1890
   888
         * {@code ReadLocks} do not support conditions.
jaroslav@1890
   889
         *
jaroslav@1890
   890
         * @throws UnsupportedOperationException always
jaroslav@1890
   891
         */
jaroslav@1890
   892
        public Condition newCondition() {
jaroslav@1890
   893
            throw new UnsupportedOperationException();
jaroslav@1890
   894
        }
jaroslav@1890
   895
jaroslav@1890
   896
        /**
jaroslav@1890
   897
         * Returns a string identifying this lock, as well as its lock state.
jaroslav@1890
   898
         * The state, in brackets, includes the String {@code "Read locks ="}
jaroslav@1890
   899
         * followed by the number of held read locks.
jaroslav@1890
   900
         *
jaroslav@1890
   901
         * @return a string identifying this lock, as well as its lock state
jaroslav@1890
   902
         */
jaroslav@1890
   903
        public String toString() {
jaroslav@1890
   904
            int r = sync.getReadLockCount();
jaroslav@1890
   905
            return super.toString() +
jaroslav@1890
   906
                "[Read locks = " + r + "]";
jaroslav@1890
   907
        }
jaroslav@1890
   908
    }
jaroslav@1890
   909
jaroslav@1890
   910
    /**
jaroslav@1890
   911
     * The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
jaroslav@1890
   912
     */
jaroslav@1890
   913
    public static class WriteLock implements Lock, java.io.Serializable {
jaroslav@1890
   914
        private static final long serialVersionUID = -4992448646407690164L;
jaroslav@1890
   915
        private final Sync sync;
jaroslav@1890
   916
jaroslav@1890
   917
        /**
jaroslav@1890
   918
         * Constructor for use by subclasses
jaroslav@1890
   919
         *
jaroslav@1890
   920
         * @param lock the outer lock object
jaroslav@1890
   921
         * @throws NullPointerException if the lock is null
jaroslav@1890
   922
         */
jaroslav@1890
   923
        protected WriteLock(ReentrantReadWriteLock lock) {
jaroslav@1890
   924
            sync = lock.sync;
jaroslav@1890
   925
        }
jaroslav@1890
   926
jaroslav@1890
   927
        /**
jaroslav@1890
   928
         * Acquires the write lock.
jaroslav@1890
   929
         *
jaroslav@1890
   930
         * <p>Acquires the write lock if neither the read nor write lock
jaroslav@1890
   931
         * are held by another thread
jaroslav@1890
   932
         * and returns immediately, setting the write lock hold count to
jaroslav@1890
   933
         * one.
jaroslav@1890
   934
         *
jaroslav@1890
   935
         * <p>If the current thread already holds the write lock then the
jaroslav@1890
   936
         * hold count is incremented by one and the method returns
jaroslav@1890
   937
         * immediately.
jaroslav@1890
   938
         *
jaroslav@1890
   939
         * <p>If the lock is held by another thread then the current
jaroslav@1890
   940
         * thread becomes disabled for thread scheduling purposes and
jaroslav@1890
   941
         * lies dormant until the write lock has been acquired, at which
jaroslav@1890
   942
         * time the write lock hold count is set to one.
jaroslav@1890
   943
         */
jaroslav@1890
   944
        public void lock() {
jaroslav@1890
   945
            sync.acquire(1);
jaroslav@1890
   946
        }
jaroslav@1890
   947
jaroslav@1890
   948
        /**
jaroslav@1890
   949
         * Acquires the write lock unless the current thread is
jaroslav@1890
   950
         * {@linkplain Thread#interrupt interrupted}.
jaroslav@1890
   951
         *
jaroslav@1890
   952
         * <p>Acquires the write lock if neither the read nor write lock
jaroslav@1890
   953
         * are held by another thread
jaroslav@1890
   954
         * and returns immediately, setting the write lock hold count to
jaroslav@1890
   955
         * one.
jaroslav@1890
   956
         *
jaroslav@1890
   957
         * <p>If the current thread already holds this lock then the
jaroslav@1890
   958
         * hold count is incremented by one and the method returns
jaroslav@1890
   959
         * immediately.
jaroslav@1890
   960
         *
jaroslav@1890
   961
         * <p>If the lock is held by another thread then the current
jaroslav@1890
   962
         * thread becomes disabled for thread scheduling purposes and
jaroslav@1890
   963
         * lies dormant until one of two things happens:
jaroslav@1890
   964
         *
jaroslav@1890
   965
         * <ul>
jaroslav@1890
   966
         *
jaroslav@1890
   967
         * <li>The write lock is acquired by the current thread; or
jaroslav@1890
   968
         *
jaroslav@1890
   969
         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
jaroslav@1890
   970
         * the current thread.
jaroslav@1890
   971
         *
jaroslav@1890
   972
         * </ul>
jaroslav@1890
   973
         *
jaroslav@1890
   974
         * <p>If the write lock is acquired by the current thread then the
jaroslav@1890
   975
         * lock hold count is set to one.
jaroslav@1890
   976
         *
jaroslav@1890
   977
         * <p>If the current thread:
jaroslav@1890
   978
         *
jaroslav@1890
   979
         * <ul>
jaroslav@1890
   980
         *
jaroslav@1890
   981
         * <li>has its interrupted status set on entry to this method;
jaroslav@1890
   982
         * or
jaroslav@1890
   983
         *
jaroslav@1890
   984
         * <li>is {@linkplain Thread#interrupt interrupted} while
jaroslav@1890
   985
         * acquiring the write lock,
jaroslav@1890
   986
         *
jaroslav@1890
   987
         * </ul>
jaroslav@1890
   988
         *
jaroslav@1890
   989
         * then {@link InterruptedException} is thrown and the current
jaroslav@1890
   990
         * thread's interrupted status is cleared.
jaroslav@1890
   991
         *
jaroslav@1890
   992
         * <p>In this implementation, as this method is an explicit
jaroslav@1890
   993
         * interruption point, preference is given to responding to
jaroslav@1890
   994
         * the interrupt over normal or reentrant acquisition of the
jaroslav@1890
   995
         * lock.
jaroslav@1890
   996
         *
jaroslav@1890
   997
         * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
   998
         */
jaroslav@1890
   999
        public void lockInterruptibly() throws InterruptedException {
jaroslav@1890
  1000
            sync.acquireInterruptibly(1);
jaroslav@1890
  1001
        }
jaroslav@1890
  1002
jaroslav@1890
  1003
        /**
jaroslav@1890
  1004
         * Acquires the write lock only if it is not held by another thread
jaroslav@1890
  1005
         * at the time of invocation.
jaroslav@1890
  1006
         *
jaroslav@1890
  1007
         * <p>Acquires the write lock if neither the read nor write lock
jaroslav@1890
  1008
         * are held by another thread
jaroslav@1890
  1009
         * and returns immediately with the value {@code true},
jaroslav@1890
  1010
         * setting the write lock hold count to one. Even when this lock has
jaroslav@1890
  1011
         * been set to use a fair ordering policy, a call to
jaroslav@1890
  1012
         * {@code tryLock()} <em>will</em> immediately acquire the
jaroslav@1890
  1013
         * lock if it is available, whether or not other threads are
jaroslav@1890
  1014
         * currently waiting for the write lock.  This &quot;barging&quot;
jaroslav@1890
  1015
         * behavior can be useful in certain circumstances, even
jaroslav@1890
  1016
         * though it breaks fairness. If you want to honor the
jaroslav@1890
  1017
         * fairness setting for this lock, then use {@link
jaroslav@1890
  1018
         * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
jaroslav@1890
  1019
         * which is almost equivalent (it also detects interruption).
jaroslav@1890
  1020
         *
jaroslav@1890
  1021
         * <p> If the current thread already holds this lock then the
jaroslav@1890
  1022
         * hold count is incremented by one and the method returns
jaroslav@1890
  1023
         * {@code true}.
jaroslav@1890
  1024
         *
jaroslav@1890
  1025
         * <p>If the lock is held by another thread then this method
jaroslav@1890
  1026
         * will return immediately with the value {@code false}.
jaroslav@1890
  1027
         *
jaroslav@1890
  1028
         * @return {@code true} if the lock was free and was acquired
jaroslav@1890
  1029
         * by the current thread, or the write lock was already held
jaroslav@1890
  1030
         * by the current thread; and {@code false} otherwise.
jaroslav@1890
  1031
         */
jaroslav@1890
  1032
        public boolean tryLock( ) {
jaroslav@1890
  1033
            return sync.tryWriteLock();
jaroslav@1890
  1034
        }
jaroslav@1890
  1035
jaroslav@1890
  1036
        /**
jaroslav@1890
  1037
         * Acquires the write lock if it is not held by another thread
jaroslav@1890
  1038
         * within the given waiting time and the current thread has
jaroslav@1890
  1039
         * not been {@linkplain Thread#interrupt interrupted}.
jaroslav@1890
  1040
         *
jaroslav@1890
  1041
         * <p>Acquires the write lock if neither the read nor write lock
jaroslav@1890
  1042
         * are held by another thread
jaroslav@1890
  1043
         * and returns immediately with the value {@code true},
jaroslav@1890
  1044
         * setting the write lock hold count to one. If this lock has been
jaroslav@1890
  1045
         * set to use a fair ordering policy then an available lock
jaroslav@1890
  1046
         * <em>will not</em> be acquired if any other threads are
jaroslav@1890
  1047
         * waiting for the write lock. This is in contrast to the {@link
jaroslav@1890
  1048
         * #tryLock()} method. If you want a timed {@code tryLock}
jaroslav@1890
  1049
         * that does permit barging on a fair lock then combine the
jaroslav@1890
  1050
         * timed and un-timed forms together:
jaroslav@1890
  1051
         *
jaroslav@1890
  1052
         * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
jaroslav@1890
  1053
         * </pre>
jaroslav@1890
  1054
         *
jaroslav@1890
  1055
         * <p>If the current thread already holds this lock then the
jaroslav@1890
  1056
         * hold count is incremented by one and the method returns
jaroslav@1890
  1057
         * {@code true}.
jaroslav@1890
  1058
         *
jaroslav@1890
  1059
         * <p>If the lock is held by another thread then the current
jaroslav@1890
  1060
         * thread becomes disabled for thread scheduling purposes and
jaroslav@1890
  1061
         * lies dormant until one of three things happens:
jaroslav@1890
  1062
         *
jaroslav@1890
  1063
         * <ul>
jaroslav@1890
  1064
         *
jaroslav@1890
  1065
         * <li>The write lock is acquired by the current thread; or
jaroslav@1890
  1066
         *
jaroslav@1890
  1067
         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
jaroslav@1890
  1068
         * the current thread; or
jaroslav@1890
  1069
         *
jaroslav@1890
  1070
         * <li>The specified waiting time elapses
jaroslav@1890
  1071
         *
jaroslav@1890
  1072
         * </ul>
jaroslav@1890
  1073
         *
jaroslav@1890
  1074
         * <p>If the write lock is acquired then the value {@code true} is
jaroslav@1890
  1075
         * returned and the write lock hold count is set to one.
jaroslav@1890
  1076
         *
jaroslav@1890
  1077
         * <p>If the current thread:
jaroslav@1890
  1078
         *
jaroslav@1890
  1079
         * <ul>
jaroslav@1890
  1080
         *
jaroslav@1890
  1081
         * <li>has its interrupted status set on entry to this method;
jaroslav@1890
  1082
         * or
jaroslav@1890
  1083
         *
jaroslav@1890
  1084
         * <li>is {@linkplain Thread#interrupt interrupted} while
jaroslav@1890
  1085
         * acquiring the write lock,
jaroslav@1890
  1086
         *
jaroslav@1890
  1087
         * </ul>
jaroslav@1890
  1088
         *
jaroslav@1890
  1089
         * then {@link InterruptedException} is thrown and the current
jaroslav@1890
  1090
         * thread's interrupted status is cleared.
jaroslav@1890
  1091
         *
jaroslav@1890
  1092
         * <p>If the specified waiting time elapses then the value
jaroslav@1890
  1093
         * {@code false} is returned.  If the time is less than or
jaroslav@1890
  1094
         * equal to zero, the method will not wait at all.
jaroslav@1890
  1095
         *
jaroslav@1890
  1096
         * <p>In this implementation, as this method is an explicit
jaroslav@1890
  1097
         * interruption point, preference is given to responding to
jaroslav@1890
  1098
         * the interrupt over normal or reentrant acquisition of the
jaroslav@1890
  1099
         * lock, and over reporting the elapse of the waiting time.
jaroslav@1890
  1100
         *
jaroslav@1890
  1101
         * @param timeout the time to wait for the write lock
jaroslav@1890
  1102
         * @param unit the time unit of the timeout argument
jaroslav@1890
  1103
         *
jaroslav@1890
  1104
         * @return {@code true} if the lock was free and was acquired
jaroslav@1890
  1105
         * by the current thread, or the write lock was already held by the
jaroslav@1890
  1106
         * current thread; and {@code false} if the waiting time
jaroslav@1890
  1107
         * elapsed before the lock could be acquired.
jaroslav@1890
  1108
         *
jaroslav@1890
  1109
         * @throws InterruptedException if the current thread is interrupted
jaroslav@1890
  1110
         * @throws NullPointerException if the time unit is null
jaroslav@1890
  1111
         *
jaroslav@1890
  1112
         */
jaroslav@1890
  1113
        public boolean tryLock(long timeout, TimeUnit unit)
jaroslav@1890
  1114
                throws InterruptedException {
jaroslav@1890
  1115
            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
jaroslav@1890
  1116
        }
jaroslav@1890
  1117
jaroslav@1890
  1118
        /**
jaroslav@1890
  1119
         * Attempts to release this lock.
jaroslav@1890
  1120
         *
jaroslav@1890
  1121
         * <p>If the current thread is the holder of this lock then
jaroslav@1890
  1122
         * the hold count is decremented. If the hold count is now
jaroslav@1890
  1123
         * zero then the lock is released.  If the current thread is
jaroslav@1890
  1124
         * not the holder of this lock then {@link
jaroslav@1890
  1125
         * IllegalMonitorStateException} is thrown.
jaroslav@1890
  1126
         *
jaroslav@1890
  1127
         * @throws IllegalMonitorStateException if the current thread does not
jaroslav@1890
  1128
         * hold this lock.
jaroslav@1890
  1129
         */
jaroslav@1890
  1130
        public void unlock() {
jaroslav@1890
  1131
            sync.release(1);
jaroslav@1890
  1132
        }
jaroslav@1890
  1133
jaroslav@1890
  1134
        /**
jaroslav@1890
  1135
         * Returns a {@link Condition} instance for use with this
jaroslav@1890
  1136
         * {@link Lock} instance.
jaroslav@1890
  1137
         * <p>The returned {@link Condition} instance supports the same
jaroslav@1890
  1138
         * usages as do the {@link Object} monitor methods ({@link
jaroslav@1890
  1139
         * Object#wait() wait}, {@link Object#notify notify}, and {@link
jaroslav@1890
  1140
         * Object#notifyAll notifyAll}) when used with the built-in
jaroslav@1890
  1141
         * monitor lock.
jaroslav@1890
  1142
         *
jaroslav@1890
  1143
         * <ul>
jaroslav@1890
  1144
         *
jaroslav@1890
  1145
         * <li>If this write lock is not held when any {@link
jaroslav@1890
  1146
         * Condition} method is called then an {@link
jaroslav@1890
  1147
         * IllegalMonitorStateException} is thrown.  (Read locks are
jaroslav@1890
  1148
         * held independently of write locks, so are not checked or
jaroslav@1890
  1149
         * affected. However it is essentially always an error to
jaroslav@1890
  1150
         * invoke a condition waiting method when the current thread
jaroslav@1890
  1151
         * has also acquired read locks, since other threads that
jaroslav@1890
  1152
         * could unblock it will not be able to acquire the write
jaroslav@1890
  1153
         * lock.)
jaroslav@1890
  1154
         *
jaroslav@1890
  1155
         * <li>When the condition {@linkplain Condition#await() waiting}
jaroslav@1890
  1156
         * methods are called the write lock is released and, before
jaroslav@1890
  1157
         * they return, the write lock is reacquired and the lock hold
jaroslav@1890
  1158
         * count restored to what it was when the method was called.
jaroslav@1890
  1159
         *
jaroslav@1890
  1160
         * <li>If a thread is {@linkplain Thread#interrupt interrupted} while
jaroslav@1890
  1161
         * waiting then the wait will terminate, an {@link
jaroslav@1890
  1162
         * InterruptedException} will be thrown, and the thread's
jaroslav@1890
  1163
         * interrupted status will be cleared.
jaroslav@1890
  1164
         *
jaroslav@1890
  1165
         * <li> Waiting threads are signalled in FIFO order.
jaroslav@1890
  1166
         *
jaroslav@1890
  1167
         * <li>The ordering of lock reacquisition for threads returning
jaroslav@1890
  1168
         * from waiting methods is the same as for threads initially
jaroslav@1890
  1169
         * acquiring the lock, which is in the default case not specified,
jaroslav@1890
  1170
         * but for <em>fair</em> locks favors those threads that have been
jaroslav@1890
  1171
         * waiting the longest.
jaroslav@1890
  1172
         *
jaroslav@1890
  1173
         * </ul>
jaroslav@1890
  1174
         *
jaroslav@1890
  1175
         * @return the Condition object
jaroslav@1890
  1176
         */
jaroslav@1890
  1177
        public Condition newCondition() {
jaroslav@1890
  1178
            return sync.newCondition();
jaroslav@1890
  1179
        }
jaroslav@1890
  1180
jaroslav@1890
  1181
        /**
jaroslav@1890
  1182
         * Returns a string identifying this lock, as well as its lock
jaroslav@1890
  1183
         * state.  The state, in brackets includes either the String
jaroslav@1890
  1184
         * {@code "Unlocked"} or the String {@code "Locked by"}
jaroslav@1890
  1185
         * followed by the {@linkplain Thread#getName name} of the owning thread.
jaroslav@1890
  1186
         *
jaroslav@1890
  1187
         * @return a string identifying this lock, as well as its lock state
jaroslav@1890
  1188
         */
jaroslav@1890
  1189
        public String toString() {
jaroslav@1890
  1190
            Thread o = sync.getOwner();
jaroslav@1890
  1191
            return super.toString() + ((o == null) ?
jaroslav@1890
  1192
                                       "[Unlocked]" :
jaroslav@1890
  1193
                                       "[Locked by thread " + o.getName() + "]");
jaroslav@1890
  1194
        }
jaroslav@1890
  1195
jaroslav@1890
  1196
        /**
jaroslav@1890
  1197
         * Queries if this write lock is held by the current thread.
jaroslav@1890
  1198
         * Identical in effect to {@link
jaroslav@1890
  1199
         * ReentrantReadWriteLock#isWriteLockedByCurrentThread}.
jaroslav@1890
  1200
         *
jaroslav@1890
  1201
         * @return {@code true} if the current thread holds this lock and
jaroslav@1890
  1202
         *         {@code false} otherwise
jaroslav@1890
  1203
         * @since 1.6
jaroslav@1890
  1204
         */
jaroslav@1890
  1205
        public boolean isHeldByCurrentThread() {
jaroslav@1890
  1206
            return sync.isHeldExclusively();
jaroslav@1890
  1207
        }
jaroslav@1890
  1208
jaroslav@1890
  1209
        /**
jaroslav@1890
  1210
         * Queries the number of holds on this write lock by the current
jaroslav@1890
  1211
         * thread.  A thread has a hold on a lock for each lock action
jaroslav@1890
  1212
         * that is not matched by an unlock action.  Identical in effect
jaroslav@1890
  1213
         * to {@link ReentrantReadWriteLock#getWriteHoldCount}.
jaroslav@1890
  1214
         *
jaroslav@1890
  1215
         * @return the number of holds on this lock by the current thread,
jaroslav@1890
  1216
         *         or zero if this lock is not held by the current thread
jaroslav@1890
  1217
         * @since 1.6
jaroslav@1890
  1218
         */
jaroslav@1890
  1219
        public int getHoldCount() {
jaroslav@1890
  1220
            return sync.getWriteHoldCount();
jaroslav@1890
  1221
        }
jaroslav@1890
  1222
    }
jaroslav@1890
  1223
jaroslav@1890
  1224
    // Instrumentation and status
jaroslav@1890
  1225
jaroslav@1890
  1226
    /**
jaroslav@1890
  1227
     * Returns {@code true} if this lock has fairness set true.
jaroslav@1890
  1228
     *
jaroslav@1890
  1229
     * @return {@code true} if this lock has fairness set true
jaroslav@1890
  1230
     */
jaroslav@1890
  1231
    public final boolean isFair() {
jaroslav@1890
  1232
        return sync instanceof FairSync;
jaroslav@1890
  1233
    }
jaroslav@1890
  1234
jaroslav@1890
  1235
    /**
jaroslav@1890
  1236
     * Returns the thread that currently owns the write lock, or
jaroslav@1890
  1237
     * {@code null} if not owned. When this method is called by a
jaroslav@1890
  1238
     * thread that is not the owner, the return value reflects a
jaroslav@1890
  1239
     * best-effort approximation of current lock status. For example,
jaroslav@1890
  1240
     * the owner may be momentarily {@code null} even if there are
jaroslav@1890
  1241
     * threads trying to acquire the lock but have not yet done so.
jaroslav@1890
  1242
     * This method is designed to facilitate construction of
jaroslav@1890
  1243
     * subclasses that provide more extensive lock monitoring
jaroslav@1890
  1244
     * facilities.
jaroslav@1890
  1245
     *
jaroslav@1890
  1246
     * @return the owner, or {@code null} if not owned
jaroslav@1890
  1247
     */
jaroslav@1890
  1248
    protected Thread getOwner() {
jaroslav@1890
  1249
        return sync.getOwner();
jaroslav@1890
  1250
    }
jaroslav@1890
  1251
jaroslav@1890
  1252
    /**
jaroslav@1890
  1253
     * Queries the number of read locks held for this lock. This
jaroslav@1890
  1254
     * method is designed for use in monitoring system state, not for
jaroslav@1890
  1255
     * synchronization control.
jaroslav@1890
  1256
     * @return the number of read locks held.
jaroslav@1890
  1257
     */
jaroslav@1890
  1258
    public int getReadLockCount() {
jaroslav@1890
  1259
        return sync.getReadLockCount();
jaroslav@1890
  1260
    }
jaroslav@1890
  1261
jaroslav@1890
  1262
    /**
jaroslav@1890
  1263
     * Queries if the write lock is held by any thread. This method is
jaroslav@1890
  1264
     * designed for use in monitoring system state, not for
jaroslav@1890
  1265
     * synchronization control.
jaroslav@1890
  1266
     *
jaroslav@1890
  1267
     * @return {@code true} if any thread holds the write lock and
jaroslav@1890
  1268
     *         {@code false} otherwise
jaroslav@1890
  1269
     */
jaroslav@1890
  1270
    public boolean isWriteLocked() {
jaroslav@1890
  1271
        return sync.isWriteLocked();
jaroslav@1890
  1272
    }
jaroslav@1890
  1273
jaroslav@1890
  1274
    /**
jaroslav@1890
  1275
     * Queries if the write lock is held by the current thread.
jaroslav@1890
  1276
     *
jaroslav@1890
  1277
     * @return {@code true} if the current thread holds the write lock and
jaroslav@1890
  1278
     *         {@code false} otherwise
jaroslav@1890
  1279
     */
jaroslav@1890
  1280
    public boolean isWriteLockedByCurrentThread() {
jaroslav@1890
  1281
        return sync.isHeldExclusively();
jaroslav@1890
  1282
    }
jaroslav@1890
  1283
jaroslav@1890
  1284
    /**
jaroslav@1890
  1285
     * Queries the number of reentrant write holds on this lock by the
jaroslav@1890
  1286
     * current thread.  A writer thread has a hold on a lock for
jaroslav@1890
  1287
     * each lock action that is not matched by an unlock action.
jaroslav@1890
  1288
     *
jaroslav@1890
  1289
     * @return the number of holds on the write lock by the current thread,
jaroslav@1890
  1290
     *         or zero if the write lock is not held by the current thread
jaroslav@1890
  1291
     */
jaroslav@1890
  1292
    public int getWriteHoldCount() {
jaroslav@1890
  1293
        return sync.getWriteHoldCount();
jaroslav@1890
  1294
    }
jaroslav@1890
  1295
jaroslav@1890
  1296
    /**
jaroslav@1890
  1297
     * Queries the number of reentrant read holds on this lock by the
jaroslav@1890
  1298
     * current thread.  A reader thread has a hold on a lock for
jaroslav@1890
  1299
     * each lock action that is not matched by an unlock action.
jaroslav@1890
  1300
     *
jaroslav@1890
  1301
     * @return the number of holds on the read lock by the current thread,
jaroslav@1890
  1302
     *         or zero if the read lock is not held by the current thread
jaroslav@1890
  1303
     * @since 1.6
jaroslav@1890
  1304
     */
jaroslav@1890
  1305
    public int getReadHoldCount() {
jaroslav@1890
  1306
        return sync.getReadHoldCount();
jaroslav@1890
  1307
    }
jaroslav@1890
  1308
jaroslav@1890
  1309
    /**
jaroslav@1890
  1310
     * Returns a collection containing threads that may be waiting to
jaroslav@1890
  1311
     * acquire the write lock.  Because the actual set of threads may
jaroslav@1890
  1312
     * change dynamically while constructing this result, the returned
jaroslav@1890
  1313
     * collection is only a best-effort estimate.  The elements of the
jaroslav@1890
  1314
     * returned collection are in no particular order.  This method is
jaroslav@1890
  1315
     * designed to facilitate construction of subclasses that provide
jaroslav@1890
  1316
     * more extensive lock monitoring facilities.
jaroslav@1890
  1317
     *
jaroslav@1890
  1318
     * @return the collection of threads
jaroslav@1890
  1319
     */
jaroslav@1890
  1320
    protected Collection<Thread> getQueuedWriterThreads() {
jaroslav@1890
  1321
        return sync.getExclusiveQueuedThreads();
jaroslav@1890
  1322
    }
jaroslav@1890
  1323
jaroslav@1890
  1324
    /**
jaroslav@1890
  1325
     * Returns a collection containing threads that may be waiting to
jaroslav@1890
  1326
     * acquire the read lock.  Because the actual set of threads may
jaroslav@1890
  1327
     * change dynamically while constructing this result, the returned
jaroslav@1890
  1328
     * collection is only a best-effort estimate.  The elements of the
jaroslav@1890
  1329
     * returned collection are in no particular order.  This method is
jaroslav@1890
  1330
     * designed to facilitate construction of subclasses that provide
jaroslav@1890
  1331
     * more extensive lock monitoring facilities.
jaroslav@1890
  1332
     *
jaroslav@1890
  1333
     * @return the collection of threads
jaroslav@1890
  1334
     */
jaroslav@1890
  1335
    protected Collection<Thread> getQueuedReaderThreads() {
jaroslav@1890
  1336
        return sync.getSharedQueuedThreads();
jaroslav@1890
  1337
    }
jaroslav@1890
  1338
jaroslav@1890
  1339
    /**
jaroslav@1890
  1340
     * Queries whether any threads are waiting to acquire the read or
jaroslav@1890
  1341
     * write lock. Note that because cancellations may occur at any
jaroslav@1890
  1342
     * time, a {@code true} return does not guarantee that any other
jaroslav@1890
  1343
     * thread will ever acquire a lock.  This method is designed
jaroslav@1890
  1344
     * primarily for use in monitoring of the system state.
jaroslav@1890
  1345
     *
jaroslav@1890
  1346
     * @return {@code true} if there may be other threads waiting to
jaroslav@1890
  1347
     *         acquire the lock
jaroslav@1890
  1348
     */
jaroslav@1890
  1349
    public final boolean hasQueuedThreads() {
jaroslav@1890
  1350
        return sync.hasQueuedThreads();
jaroslav@1890
  1351
    }
jaroslav@1890
  1352
jaroslav@1890
  1353
    /**
jaroslav@1890
  1354
     * Queries whether the given thread is waiting to acquire either
jaroslav@1890
  1355
     * the read or write lock. Note that because cancellations may
jaroslav@1890
  1356
     * occur at any time, a {@code true} return does not guarantee
jaroslav@1890
  1357
     * that this thread will ever acquire a lock.  This method is
jaroslav@1890
  1358
     * designed primarily for use in monitoring of the system state.
jaroslav@1890
  1359
     *
jaroslav@1890
  1360
     * @param thread the thread
jaroslav@1890
  1361
     * @return {@code true} if the given thread is queued waiting for this lock
jaroslav@1890
  1362
     * @throws NullPointerException if the thread is null
jaroslav@1890
  1363
     */
jaroslav@1890
  1364
    public final boolean hasQueuedThread(Thread thread) {
jaroslav@1890
  1365
        return sync.isQueued(thread);
jaroslav@1890
  1366
    }
jaroslav@1890
  1367
jaroslav@1890
  1368
    /**
jaroslav@1890
  1369
     * Returns an estimate of the number of threads waiting to acquire
jaroslav@1890
  1370
     * either the read or write lock.  The value is only an estimate
jaroslav@1890
  1371
     * because the number of threads may change dynamically while this
jaroslav@1890
  1372
     * method traverses internal data structures.  This method is
jaroslav@1890
  1373
     * designed for use in monitoring of the system state, not for
jaroslav@1890
  1374
     * synchronization control.
jaroslav@1890
  1375
     *
jaroslav@1890
  1376
     * @return the estimated number of threads waiting for this lock
jaroslav@1890
  1377
     */
jaroslav@1890
  1378
    public final int getQueueLength() {
jaroslav@1890
  1379
        return sync.getQueueLength();
jaroslav@1890
  1380
    }
jaroslav@1890
  1381
jaroslav@1890
  1382
    /**
jaroslav@1890
  1383
     * Returns a collection containing threads that may be waiting to
jaroslav@1890
  1384
     * acquire either the read or write lock.  Because the actual set
jaroslav@1890
  1385
     * of threads may change dynamically while constructing this
jaroslav@1890
  1386
     * result, the returned collection is only a best-effort estimate.
jaroslav@1890
  1387
     * The elements of the returned collection are in no particular
jaroslav@1890
  1388
     * order.  This method is designed to facilitate construction of
jaroslav@1890
  1389
     * subclasses that provide more extensive monitoring facilities.
jaroslav@1890
  1390
     *
jaroslav@1890
  1391
     * @return the collection of threads
jaroslav@1890
  1392
     */
jaroslav@1890
  1393
    protected Collection<Thread> getQueuedThreads() {
jaroslav@1890
  1394
        return sync.getQueuedThreads();
jaroslav@1890
  1395
    }
jaroslav@1890
  1396
jaroslav@1890
  1397
    /**
jaroslav@1890
  1398
     * Queries whether any threads are waiting on the given condition
jaroslav@1890
  1399
     * associated with the write lock. Note that because timeouts and
jaroslav@1890
  1400
     * interrupts may occur at any time, a {@code true} return does
jaroslav@1890
  1401
     * not guarantee that a future {@code signal} will awaken any
jaroslav@1890
  1402
     * threads.  This method is designed primarily for use in
jaroslav@1890
  1403
     * monitoring of the system state.
jaroslav@1890
  1404
     *
jaroslav@1890
  1405
     * @param condition the condition
jaroslav@1890
  1406
     * @return {@code true} if there are any waiting threads
jaroslav@1890
  1407
     * @throws IllegalMonitorStateException if this lock is not held
jaroslav@1890
  1408
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
  1409
     *         not associated with this lock
jaroslav@1890
  1410
     * @throws NullPointerException if the condition is null
jaroslav@1890
  1411
     */
jaroslav@1890
  1412
    public boolean hasWaiters(Condition condition) {
jaroslav@1890
  1413
        if (condition == null)
jaroslav@1890
  1414
            throw new NullPointerException();
jaroslav@1890
  1415
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
jaroslav@1890
  1416
            throw new IllegalArgumentException("not owner");
jaroslav@1890
  1417
        return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
jaroslav@1890
  1418
    }
jaroslav@1890
  1419
jaroslav@1890
  1420
    /**
jaroslav@1890
  1421
     * Returns an estimate of the number of threads waiting on the
jaroslav@1890
  1422
     * given condition associated with the write lock. Note that because
jaroslav@1890
  1423
     * timeouts and interrupts may occur at any time, the estimate
jaroslav@1890
  1424
     * serves only as an upper bound on the actual number of waiters.
jaroslav@1890
  1425
     * This method is designed for use in monitoring of the system
jaroslav@1890
  1426
     * state, not for synchronization control.
jaroslav@1890
  1427
     *
jaroslav@1890
  1428
     * @param condition the condition
jaroslav@1890
  1429
     * @return the estimated number of waiting threads
jaroslav@1890
  1430
     * @throws IllegalMonitorStateException if this lock is not held
jaroslav@1890
  1431
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
  1432
     *         not associated with this lock
jaroslav@1890
  1433
     * @throws NullPointerException if the condition is null
jaroslav@1890
  1434
     */
jaroslav@1890
  1435
    public int getWaitQueueLength(Condition condition) {
jaroslav@1890
  1436
        if (condition == null)
jaroslav@1890
  1437
            throw new NullPointerException();
jaroslav@1890
  1438
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
jaroslav@1890
  1439
            throw new IllegalArgumentException("not owner");
jaroslav@1890
  1440
        return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
jaroslav@1890
  1441
    }
jaroslav@1890
  1442
jaroslav@1890
  1443
    /**
jaroslav@1890
  1444
     * Returns a collection containing those threads that may be
jaroslav@1890
  1445
     * waiting on the given condition associated with the write lock.
jaroslav@1890
  1446
     * Because the actual set of threads may change dynamically while
jaroslav@1890
  1447
     * constructing this result, the returned collection is only a
jaroslav@1890
  1448
     * best-effort estimate. The elements of the returned collection
jaroslav@1890
  1449
     * are in no particular order.  This method is designed to
jaroslav@1890
  1450
     * facilitate construction of subclasses that provide more
jaroslav@1890
  1451
     * extensive condition monitoring facilities.
jaroslav@1890
  1452
     *
jaroslav@1890
  1453
     * @param condition the condition
jaroslav@1890
  1454
     * @return the collection of threads
jaroslav@1890
  1455
     * @throws IllegalMonitorStateException if this lock is not held
jaroslav@1890
  1456
     * @throws IllegalArgumentException if the given condition is
jaroslav@1890
  1457
     *         not associated with this lock
jaroslav@1890
  1458
     * @throws NullPointerException if the condition is null
jaroslav@1890
  1459
     */
jaroslav@1890
  1460
    protected Collection<Thread> getWaitingThreads(Condition condition) {
jaroslav@1890
  1461
        if (condition == null)
jaroslav@1890
  1462
            throw new NullPointerException();
jaroslav@1890
  1463
        if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
jaroslav@1890
  1464
            throw new IllegalArgumentException("not owner");
jaroslav@1890
  1465
        return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
jaroslav@1890
  1466
    }
jaroslav@1890
  1467
jaroslav@1890
  1468
    /**
jaroslav@1890
  1469
     * Returns a string identifying this lock, as well as its lock state.
jaroslav@1890
  1470
     * The state, in brackets, includes the String {@code "Write locks ="}
jaroslav@1890
  1471
     * followed by the number of reentrantly held write locks, and the
jaroslav@1890
  1472
     * String {@code "Read locks ="} followed by the number of held
jaroslav@1890
  1473
     * read locks.
jaroslav@1890
  1474
     *
jaroslav@1890
  1475
     * @return a string identifying this lock, as well as its lock state
jaroslav@1890
  1476
     */
jaroslav@1890
  1477
    public String toString() {
jaroslav@1890
  1478
        int c = sync.getCount();
jaroslav@1890
  1479
        int w = Sync.exclusiveCount(c);
jaroslav@1890
  1480
        int r = Sync.sharedCount(c);
jaroslav@1890
  1481
jaroslav@1890
  1482
        return super.toString() +
jaroslav@1890
  1483
            "[Write locks = " + w + ", Read locks = " + r + "]";
jaroslav@1890
  1484
    }
jaroslav@1890
  1485
jaroslav@1890
  1486
}