0N/A/*
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/A/*
0N/A * This file is available under and governed by the GNU General Public
0N/A * License version 2 only, as published by the Free Software Foundation.
0N/A * However, the following notice accompanied the original version of this
0N/A * file:
0N/A *
0N/A * Written by Doug Lea with assistance from members of JCP JSR-166
0N/A * Expert Group and released to the public domain, as explained at
3984N/A * http://creativecommons.org/publicdomain/zero/1.0/
0N/A */
0N/A
0N/Apackage java.util.concurrent.locks;
0N/Aimport java.util.concurrent.*;
0N/Aimport java.util.concurrent.atomic.*;
0N/Aimport java.util.*;
0N/A
0N/A/**
0N/A * An implementation of {@link ReadWriteLock} supporting similar
0N/A * semantics to {@link ReentrantLock}.
0N/A * <p>This class has the following properties:
0N/A *
0N/A * <ul>
0N/A * <li><b>Acquisition order</b>
0N/A *
0N/A * <p> This class does not impose a reader or writer preference
0N/A * ordering for lock access. However, it does support an optional
0N/A * <em>fairness</em> policy.
0N/A *
0N/A * <dl>
0N/A * <dt><b><i>Non-fair mode (default)</i></b>
0N/A * <dd>When constructed as non-fair (the default), the order of entry
0N/A * to the read and write lock is unspecified, subject to reentrancy
0N/A * constraints. A nonfair lock that is continuously contended may
0N/A * indefinitely postpone one or more reader or writer threads, but
0N/A * will normally have higher throughput than a fair lock.
0N/A * <p>
0N/A *
0N/A * <dt><b><i>Fair mode</i></b>
0N/A * <dd> When constructed as fair, threads contend for entry using an
0N/A * approximately arrival-order policy. When the currently held lock
0N/A * is released either the longest-waiting single writer thread will
0N/A * be assigned the write lock, or if there is a group of reader threads
0N/A * waiting longer than all waiting writer threads, that group will be
0N/A * assigned the read lock.
0N/A *
0N/A * <p>A thread that tries to acquire a fair read lock (non-reentrantly)
0N/A * will block if either the write lock is held, or there is a waiting
0N/A * writer thread. The thread will not acquire the read lock until
0N/A * after the oldest currently waiting writer thread has acquired and
0N/A * released the write lock. Of course, if a waiting writer abandons
0N/A * its wait, leaving one or more reader threads as the longest waiters
0N/A * in the queue with the write lock free, then those readers will be
0N/A * assigned the read lock.
0N/A *
0N/A * <p>A thread that tries to acquire a fair write lock (non-reentrantly)
0N/A * will block unless both the read lock and write lock are free (which
0N/A * implies there are no waiting threads). (Note that the non-blocking
0N/A * {@link ReadLock#tryLock()} and {@link WriteLock#tryLock()} methods
0N/A * do not honor this fair setting and will acquire the lock if it is
0N/A * possible, regardless of waiting threads.)
0N/A * <p>
0N/A * </dl>
0N/A *
0N/A * <li><b>Reentrancy</b>
0N/A *
0N/A * <p>This lock allows both readers and writers to reacquire read or
0N/A * write locks in the style of a {@link ReentrantLock}. Non-reentrant
0N/A * readers are not allowed until all write locks held by the writing
0N/A * thread have been released.
0N/A *
0N/A * <p>Additionally, a writer can acquire the read lock, but not
0N/A * vice-versa. Among other applications, reentrancy can be useful
0N/A * when write locks are held during calls or callbacks to methods that
0N/A * perform reads under read locks. If a reader tries to acquire the
0N/A * write lock it will never succeed.
0N/A *
0N/A * <li><b>Lock downgrading</b>
0N/A * <p>Reentrancy also allows downgrading from the write lock to a read lock,
0N/A * by acquiring the write lock, then the read lock and then releasing the
0N/A * write lock. However, upgrading from a read lock to the write lock is
0N/A * <b>not</b> possible.
0N/A *
0N/A * <li><b>Interruption of lock acquisition</b>
0N/A * <p>The read lock and write lock both support interruption during lock
0N/A * acquisition.
0N/A *
0N/A * <li><b>{@link Condition} support</b>
0N/A * <p>The write lock provides a {@link Condition} implementation that
0N/A * behaves in the same way, with respect to the write lock, as the
0N/A * {@link Condition} implementation provided by
0N/A * {@link ReentrantLock#newCondition} does for {@link ReentrantLock}.
0N/A * This {@link Condition} can, of course, only be used with the write lock.
0N/A *
0N/A * <p>The read lock does not support a {@link Condition} and
0N/A * {@code readLock().newCondition()} throws
0N/A * {@code UnsupportedOperationException}.
0N/A *
0N/A * <li><b>Instrumentation</b>
0N/A * <p>This class supports methods to determine whether locks
0N/A * are held or contended. These methods are designed for monitoring
0N/A * system state, not for synchronization control.
0N/A * </ul>
0N/A *
0N/A * <p>Serialization of this class behaves in the same way as built-in
0N/A * locks: a deserialized lock is in the unlocked state, regardless of
0N/A * its state when serialized.
0N/A *
0N/A * <p><b>Sample usages</b>. Here is a code sketch showing how to perform
0N/A * lock downgrading after updating a cache (exception handling is
0N/A * particularly tricky when handling multiple locks in a non-nested
0N/A * fashion):
0N/A *
0N/A * <pre> {@code
0N/A * class CachedData {
0N/A * Object data;
0N/A * volatile boolean cacheValid;
0N/A * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
0N/A *
0N/A * void processCachedData() {
0N/A * rwl.readLock().lock();
0N/A * if (!cacheValid) {
0N/A * // Must release read lock before acquiring write lock
0N/A * rwl.readLock().unlock();
0N/A * rwl.writeLock().lock();
0N/A * try {
0N/A * // Recheck state because another thread might have
0N/A * // acquired write lock and changed state before we did.
0N/A * if (!cacheValid) {
0N/A * data = ...
0N/A * cacheValid = true;
0N/A * }
0N/A * // Downgrade by acquiring read lock before releasing write lock
0N/A * rwl.readLock().lock();
3203N/A * } finally {
0N/A * rwl.writeLock().unlock(); // Unlock write, still hold read
0N/A * }
0N/A * }
0N/A *
0N/A * try {
0N/A * use(data);
0N/A * } finally {
0N/A * rwl.readLock().unlock();
0N/A * }
0N/A * }
0N/A * }}</pre>
0N/A *
0N/A * ReentrantReadWriteLocks can be used to improve concurrency in some
0N/A * uses of some kinds of Collections. This is typically worthwhile
0N/A * only when the collections are expected to be large, accessed by
0N/A * more reader threads than writer threads, and entail operations with
0N/A * overhead that outweighs synchronization overhead. For example, here
0N/A * is a class using a TreeMap that is expected to be large and
0N/A * concurrently accessed.
0N/A *
0N/A * <pre>{@code
0N/A * class RWDictionary {
0N/A * private final Map<String, Data> m = new TreeMap<String, Data>();
0N/A * private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
0N/A * private final Lock r = rwl.readLock();
0N/A * private final Lock w = rwl.writeLock();
0N/A *
0N/A * public Data get(String key) {
0N/A * r.lock();
0N/A * try { return m.get(key); }
0N/A * finally { r.unlock(); }
0N/A * }
0N/A * public String[] allKeys() {
0N/A * r.lock();
0N/A * try { return m.keySet().toArray(); }
0N/A * finally { r.unlock(); }
0N/A * }
0N/A * public Data put(String key, Data value) {
0N/A * w.lock();
0N/A * try { return m.put(key, value); }
0N/A * finally { w.unlock(); }
0N/A * }
0N/A * public void clear() {
0N/A * w.lock();
0N/A * try { m.clear(); }
0N/A * finally { w.unlock(); }
0N/A * }
0N/A * }}</pre>
0N/A *
0N/A * <h3>Implementation Notes</h3>
0N/A *
0N/A * <p>This lock supports a maximum of 65535 recursive write locks
0N/A * and 65535 read locks. Attempts to exceed these limits result in
0N/A * {@link Error} throws from locking methods.
0N/A *
0N/A * @since 1.5
0N/A * @author Doug Lea
0N/A *
0N/A */
3203N/Apublic class ReentrantReadWriteLock
3203N/A implements ReadWriteLock, java.io.Serializable {
0N/A private static final long serialVersionUID = -6992448646407690164L;
0N/A /** Inner class providing readlock */
0N/A private final ReentrantReadWriteLock.ReadLock readerLock;
0N/A /** Inner class providing writelock */
0N/A private final ReentrantReadWriteLock.WriteLock writerLock;
0N/A /** Performs all synchronization mechanics */
39N/A final Sync sync;
0N/A
0N/A /**
0N/A * Creates a new {@code ReentrantReadWriteLock} with
0N/A * default (nonfair) ordering properties.
0N/A */
0N/A public ReentrantReadWriteLock() {
0N/A this(false);
0N/A }
0N/A
0N/A /**
0N/A * Creates a new {@code ReentrantReadWriteLock} with
0N/A * the given fairness policy.
0N/A *
0N/A * @param fair {@code true} if this lock should use a fair ordering policy
0N/A */
0N/A public ReentrantReadWriteLock(boolean fair) {
39N/A sync = fair ? new FairSync() : new NonfairSync();
0N/A readerLock = new ReadLock(this);
0N/A writerLock = new WriteLock(this);
0N/A }
0N/A
0N/A public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
0N/A public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }
0N/A
0N/A /**
0N/A * Synchronization implementation for ReentrantReadWriteLock.
0N/A * Subclassed into fair and nonfair versions.
0N/A */
3203N/A abstract static class Sync extends AbstractQueuedSynchronizer {
0N/A private static final long serialVersionUID = 6317671515068378041L;
0N/A
0N/A /*
0N/A * Read vs write count extraction constants and functions.
39N/A * Lock state is logically divided into two unsigned shorts:
39N/A * The lower one representing the exclusive (writer) lock hold count,
0N/A * and the upper the shared (reader) hold count.
0N/A */
0N/A
0N/A static final int SHARED_SHIFT = 16;
0N/A static final int SHARED_UNIT = (1 << SHARED_SHIFT);
0N/A static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
0N/A static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
0N/A
0N/A /** Returns the number of shared holds represented in count */
0N/A static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
0N/A /** Returns the number of exclusive holds represented in count */
0N/A static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
0N/A
0N/A /**
0N/A * A counter for per-thread read hold counts.
0N/A * Maintained as a ThreadLocal; cached in cachedHoldCounter
0N/A */
0N/A static final class HoldCounter {
1025N/A int count = 0;
0N/A // Use id, not reference, to avoid garbage retention
0N/A final long tid = Thread.currentThread().getId();
0N/A }
0N/A
0N/A /**
0N/A * ThreadLocal subclass. Easiest to explicitly define for sake
0N/A * of deserialization mechanics.
0N/A */
0N/A static final class ThreadLocalHoldCounter
0N/A extends ThreadLocal<HoldCounter> {
0N/A public HoldCounter initialValue() {
0N/A return new HoldCounter();
0N/A }
0N/A }
0N/A
0N/A /**
1025N/A * The number of reentrant read locks held by current thread.
0N/A * Initialized only in constructor and readObject.
1025N/A * Removed whenever a thread's read hold count drops to 0.
0N/A */
39N/A private transient ThreadLocalHoldCounter readHolds;
0N/A
0N/A /**
0N/A * The hold count of the last thread to successfully acquire
0N/A * readLock. This saves ThreadLocal lookup in the common case
0N/A * where the next thread to release is the last one to
0N/A * acquire. This is non-volatile since it is just used
0N/A * as a heuristic, and would be great for threads to cache.
1025N/A *
1025N/A * <p>Can outlive the Thread for which it is caching the read
1025N/A * hold count, but avoids garbage retention by not retaining a
1025N/A * reference to the Thread.
1025N/A *
1025N/A * <p>Accessed via a benign data race; relies on the memory
1025N/A * model's final field and out-of-thin-air guarantees.
0N/A */
39N/A private transient HoldCounter cachedHoldCounter;
39N/A
39N/A /**
39N/A * firstReader is the first thread to have acquired the read lock.
39N/A * firstReaderHoldCount is firstReader's hold count.
1025N/A *
1025N/A * <p>More precisely, firstReader is the unique thread that last
1025N/A * changed the shared count from 0 to 1, and has not released the
1025N/A * read lock since then; null if there is no such thread.
1025N/A *
1025N/A * <p>Cannot cause garbage retention unless the thread terminated
1025N/A * without relinquishing its read locks, since tryReleaseShared
1025N/A * sets it to null.
1025N/A *
1025N/A * <p>Accessed via a benign data race; relies on the memory
1025N/A * model's out-of-thin-air guarantees for references.
1025N/A *
1025N/A * <p>This allows tracking of read holds for uncontended read
39N/A * locks to be very cheap.
39N/A */
1025N/A private transient Thread firstReader = null;
39N/A private transient int firstReaderHoldCount;
0N/A
0N/A Sync() {
0N/A readHolds = new ThreadLocalHoldCounter();
0N/A setState(getState()); // ensures visibility of readHolds
0N/A }
0N/A
0N/A /*
0N/A * Acquires and releases use the same code for fair and
0N/A * nonfair locks, but differ in whether/how they allow barging
0N/A * when queues are non-empty.
0N/A */
0N/A
0N/A /**
0N/A * Returns true if the current thread, when trying to acquire
0N/A * the read lock, and otherwise eligible to do so, should block
0N/A * because of policy for overtaking other waiting threads.
0N/A */
0N/A abstract boolean readerShouldBlock();
0N/A
0N/A /**
0N/A * Returns true if the current thread, when trying to acquire
0N/A * the write lock, and otherwise eligible to do so, should block
0N/A * because of policy for overtaking other waiting threads.
0N/A */
0N/A abstract boolean writerShouldBlock();
0N/A
0N/A /*
0N/A * Note that tryRelease and tryAcquire can be called by
0N/A * Conditions. So it is possible that their arguments contain
0N/A * both read and write holds that are all released during a
0N/A * condition wait and re-established in tryAcquire.
0N/A */
0N/A
0N/A protected final boolean tryRelease(int releases) {
0N/A if (!isHeldExclusively())
0N/A throw new IllegalMonitorStateException();
0N/A int nextc = getState() - releases;
0N/A boolean free = exclusiveCount(nextc) == 0;
0N/A if (free)
0N/A setExclusiveOwnerThread(null);
0N/A setState(nextc);
0N/A return free;
0N/A }
0N/A
0N/A protected final boolean tryAcquire(int acquires) {
0N/A /*
0N/A * Walkthrough:
0N/A * 1. If read count nonzero or write count nonzero
0N/A * and owner is a different thread, fail.
0N/A * 2. If count would saturate, fail. (This can only
0N/A * happen if count is already nonzero.)
0N/A * 3. Otherwise, this thread is eligible for lock if
0N/A * it is either a reentrant acquire or
0N/A * queue policy allows it. If so, update state
0N/A * and set owner.
0N/A */
0N/A Thread current = Thread.currentThread();
0N/A int c = getState();
0N/A int w = exclusiveCount(c);
0N/A if (c != 0) {
0N/A // (Note: if c != 0 and w == 0 then shared count != 0)
0N/A if (w == 0 || current != getExclusiveOwnerThread())
0N/A return false;
0N/A if (w + exclusiveCount(acquires) > MAX_COUNT)
0N/A throw new Error("Maximum lock count exceeded");
0N/A // Reentrant acquire
0N/A setState(c + acquires);
0N/A return true;
0N/A }
0N/A if (writerShouldBlock() ||
0N/A !compareAndSetState(c, c + acquires))
0N/A return false;
0N/A setExclusiveOwnerThread(current);
0N/A return true;
0N/A }
0N/A
0N/A protected final boolean tryReleaseShared(int unused) {
1025N/A Thread current = Thread.currentThread();
1025N/A if (firstReader == current) {
39N/A // assert firstReaderHoldCount > 0;
39N/A if (firstReaderHoldCount == 1)
1025N/A firstReader = null;
39N/A else
39N/A firstReaderHoldCount--;
39N/A } else {
39N/A HoldCounter rh = cachedHoldCounter;
1025N/A if (rh == null || rh.tid != current.getId())
39N/A rh = readHolds.get();
39N/A int count = rh.count;
39N/A if (count <= 1) {
39N/A readHolds.remove();
39N/A if (count <= 0)
39N/A throw unmatchedUnlockException();
39N/A }
39N/A --rh.count;
39N/A }
0N/A for (;;) {
0N/A int c = getState();
0N/A int nextc = c - SHARED_UNIT;
0N/A if (compareAndSetState(c, nextc))
1025N/A // Releasing the read lock has no effect on readers,
1025N/A // but it may allow waiting writers to proceed if
1025N/A // both read and write locks are now free.
0N/A return nextc == 0;
0N/A }
0N/A }
0N/A
39N/A private IllegalMonitorStateException unmatchedUnlockException() {
39N/A return new IllegalMonitorStateException(
39N/A "attempt to unlock read lock, not locked by current thread");
39N/A }
39N/A
0N/A protected final int tryAcquireShared(int unused) {
0N/A /*
0N/A * Walkthrough:
0N/A * 1. If write lock held by another thread, fail.
39N/A * 2. Otherwise, this thread is eligible for
0N/A * lock wrt state, so ask if it should block
0N/A * because of queue policy. If not, try
0N/A * to grant by CASing state and updating count.
0N/A * Note that step does not check for reentrant
0N/A * acquires, which is postponed to full version
0N/A * to avoid having to check hold count in
0N/A * the more typical non-reentrant case.
39N/A * 3. If step 2 fails either because thread
39N/A * apparently not eligible or CAS fails or count
39N/A * saturated, chain to version with full retry loop.
0N/A */
0N/A Thread current = Thread.currentThread();
0N/A int c = getState();
0N/A if (exclusiveCount(c) != 0 &&
0N/A getExclusiveOwnerThread() != current)
0N/A return -1;
39N/A int r = sharedCount(c);
0N/A if (!readerShouldBlock() &&
39N/A r < MAX_COUNT &&
0N/A compareAndSetState(c, c + SHARED_UNIT)) {
39N/A if (r == 0) {
1025N/A firstReader = current;
39N/A firstReaderHoldCount = 1;
1025N/A } else if (firstReader == current) {
39N/A firstReaderHoldCount++;
39N/A } else {
39N/A HoldCounter rh = cachedHoldCounter;
1025N/A if (rh == null || rh.tid != current.getId())
39N/A cachedHoldCounter = rh = readHolds.get();
39N/A else if (rh.count == 0)
39N/A readHolds.set(rh);
39N/A rh.count++;
39N/A }
0N/A return 1;
0N/A }
0N/A return fullTryAcquireShared(current);
0N/A }
0N/A
0N/A /**
0N/A * Full version of acquire for reads, that handles CAS misses
0N/A * and reentrant reads not dealt with in tryAcquireShared.
0N/A */
0N/A final int fullTryAcquireShared(Thread current) {
0N/A /*
0N/A * This code is in part redundant with that in
0N/A * tryAcquireShared but is simpler overall by not
0N/A * complicating tryAcquireShared with interactions between
0N/A * retries and lazily reading hold counts.
0N/A */
39N/A HoldCounter rh = null;
0N/A for (;;) {
0N/A int c = getState();
39N/A if (exclusiveCount(c) != 0) {
39N/A if (getExclusiveOwnerThread() != current)
39N/A return -1;
39N/A // else we hold the exclusive lock; blocking here
39N/A // would cause deadlock.
39N/A } else if (readerShouldBlock()) {
39N/A // Make sure we're not acquiring read lock reentrantly
1025N/A if (firstReader == current) {
39N/A // assert firstReaderHoldCount > 0;
39N/A } else {
39N/A if (rh == null) {
39N/A rh = cachedHoldCounter;
1025N/A if (rh == null || rh.tid != current.getId()) {
39N/A rh = readHolds.get();
39N/A if (rh.count == 0)
39N/A readHolds.remove();
39N/A }
39N/A }
39N/A if (rh.count == 0)
39N/A return -1;
39N/A }
39N/A }
0N/A if (sharedCount(c) == MAX_COUNT)
0N/A throw new Error("Maximum lock count exceeded");
0N/A if (compareAndSetState(c, c + SHARED_UNIT)) {
39N/A if (sharedCount(c) == 0) {
1025N/A firstReader = current;
39N/A firstReaderHoldCount = 1;
1025N/A } else if (firstReader == current) {
39N/A firstReaderHoldCount++;
39N/A } else {
1025N/A if (rh == null)
39N/A rh = cachedHoldCounter;
1025N/A if (rh == null || rh.tid != current.getId())
1025N/A rh = readHolds.get();
1025N/A else if (rh.count == 0)
39N/A readHolds.set(rh);
1025N/A rh.count++;
39N/A cachedHoldCounter = rh; // cache for release
39N/A }
0N/A return 1;
0N/A }
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Performs tryLock for write, enabling barging in both modes.
0N/A * This is identical in effect to tryAcquire except for lack
39N/A * of calls to writerShouldBlock.
0N/A */
0N/A final boolean tryWriteLock() {
0N/A Thread current = Thread.currentThread();
0N/A int c = getState();
0N/A if (c != 0) {
0N/A int w = exclusiveCount(c);
39N/A if (w == 0 || current != getExclusiveOwnerThread())
0N/A return false;
0N/A if (w == MAX_COUNT)
0N/A throw new Error("Maximum lock count exceeded");
0N/A }
0N/A if (!compareAndSetState(c, c + 1))
0N/A return false;
0N/A setExclusiveOwnerThread(current);
0N/A return true;
0N/A }
0N/A
0N/A /**
0N/A * Performs tryLock for read, enabling barging in both modes.
0N/A * This is identical in effect to tryAcquireShared except for
39N/A * lack of calls to readerShouldBlock.
0N/A */
0N/A final boolean tryReadLock() {
0N/A Thread current = Thread.currentThread();
0N/A for (;;) {
0N/A int c = getState();
0N/A if (exclusiveCount(c) != 0 &&
0N/A getExclusiveOwnerThread() != current)
0N/A return false;
39N/A int r = sharedCount(c);
39N/A if (r == MAX_COUNT)
0N/A throw new Error("Maximum lock count exceeded");
0N/A if (compareAndSetState(c, c + SHARED_UNIT)) {
39N/A if (r == 0) {
1025N/A firstReader = current;
39N/A firstReaderHoldCount = 1;
1025N/A } else if (firstReader == current) {
39N/A firstReaderHoldCount++;
39N/A } else {
39N/A HoldCounter rh = cachedHoldCounter;
1025N/A if (rh == null || rh.tid != current.getId())
39N/A cachedHoldCounter = rh = readHolds.get();
39N/A else if (rh.count == 0)
39N/A readHolds.set(rh);
39N/A rh.count++;
39N/A }
0N/A return true;
0N/A }
0N/A }
0N/A }
0N/A
0N/A protected final boolean isHeldExclusively() {
0N/A // While we must in general read state before owner,
0N/A // we don't need to do so to check if current thread is owner
0N/A return getExclusiveOwnerThread() == Thread.currentThread();
0N/A }
0N/A
0N/A // Methods relayed to outer class
0N/A
0N/A final ConditionObject newCondition() {
0N/A return new ConditionObject();
0N/A }
0N/A
0N/A final Thread getOwner() {
0N/A // Must read state before owner to ensure memory consistency
3203N/A return ((exclusiveCount(getState()) == 0) ?
0N/A null :
0N/A getExclusiveOwnerThread());
0N/A }
0N/A
0N/A final int getReadLockCount() {
0N/A return sharedCount(getState());
0N/A }
0N/A
0N/A final boolean isWriteLocked() {
0N/A return exclusiveCount(getState()) != 0;
0N/A }
0N/A
0N/A final int getWriteHoldCount() {
0N/A return isHeldExclusively() ? exclusiveCount(getState()) : 0;
0N/A }
0N/A
0N/A final int getReadHoldCount() {
39N/A if (getReadLockCount() == 0)
39N/A return 0;
39N/A
1025N/A Thread current = Thread.currentThread();
1025N/A if (firstReader == current)
39N/A return firstReaderHoldCount;
39N/A
39N/A HoldCounter rh = cachedHoldCounter;
1025N/A if (rh != null && rh.tid == current.getId())
39N/A return rh.count;
39N/A
39N/A int count = readHolds.get().count;
39N/A if (count == 0) readHolds.remove();
39N/A return count;
0N/A }
0N/A
0N/A /**
0N/A * Reconstitute this lock instance from a stream
0N/A * @param s the stream
0N/A */
0N/A private void readObject(java.io.ObjectInputStream s)
0N/A throws java.io.IOException, ClassNotFoundException {
0N/A s.defaultReadObject();
0N/A readHolds = new ThreadLocalHoldCounter();
0N/A setState(0); // reset to unlocked state
0N/A }
0N/A
0N/A final int getCount() { return getState(); }
0N/A }
0N/A
0N/A /**
0N/A * Nonfair version of Sync
0N/A */
3203N/A static final class NonfairSync extends Sync {
0N/A private static final long serialVersionUID = -8159625535654395037L;
0N/A final boolean writerShouldBlock() {
0N/A return false; // writers can always barge
0N/A }
0N/A final boolean readerShouldBlock() {
0N/A /* As a heuristic to avoid indefinite writer starvation,
0N/A * block if the thread that momentarily appears to be head
0N/A * of queue, if one exists, is a waiting writer. This is
0N/A * only a probabilistic effect since a new reader will not
0N/A * block if there is a waiting writer behind other enabled
0N/A * readers that have not yet drained from the queue.
0N/A */
0N/A return apparentlyFirstQueuedIsExclusive();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Fair version of Sync
0N/A */
3203N/A static final class FairSync extends Sync {
0N/A private static final long serialVersionUID = -2274990926593161451L;
0N/A final boolean writerShouldBlock() {
0N/A return hasQueuedPredecessors();
0N/A }
0N/A final boolean readerShouldBlock() {
0N/A return hasQueuedPredecessors();
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * The lock returned by method {@link ReentrantReadWriteLock#readLock}.
0N/A */
3203N/A public static class ReadLock implements Lock, java.io.Serializable {
0N/A private static final long serialVersionUID = -5992448646407690164L;
0N/A private final Sync sync;
0N/A
0N/A /**
0N/A * Constructor for use by subclasses
0N/A *
0N/A * @param lock the outer lock object
0N/A * @throws NullPointerException if the lock is null
0N/A */
0N/A protected ReadLock(ReentrantReadWriteLock lock) {
0N/A sync = lock.sync;
0N/A }
0N/A
0N/A /**
0N/A * Acquires the read lock.
0N/A *
0N/A * <p>Acquires the read lock if the write lock is not held by
0N/A * another thread and returns immediately.
0N/A *
0N/A * <p>If the write lock is held by another thread then
0N/A * the current thread becomes disabled for thread scheduling
0N/A * purposes and lies dormant until the read lock has been acquired.
0N/A */
0N/A public void lock() {
0N/A sync.acquireShared(1);
0N/A }
0N/A
0N/A /**
0N/A * Acquires the read lock unless the current thread is
0N/A * {@linkplain Thread#interrupt interrupted}.
0N/A *
0N/A * <p>Acquires the read lock if the write lock is not held
0N/A * by another thread and returns immediately.
0N/A *
0N/A * <p>If the write lock is held by another thread then the
0N/A * current thread becomes disabled for thread scheduling
0N/A * purposes and lies dormant until one of two things happens:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>The read lock is acquired by the current thread; or
0N/A *
0N/A * <li>Some other thread {@linkplain Thread#interrupt interrupts}
0N/A * the current thread.
0N/A *
0N/A * </ul>
0N/A *
0N/A * <p>If the current thread:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>has its interrupted status set on entry to this method; or
0N/A *
0N/A * <li>is {@linkplain Thread#interrupt interrupted} while
0N/A * acquiring the read lock,
0N/A *
0N/A * </ul>
0N/A *
0N/A * then {@link InterruptedException} is thrown and the current
0N/A * thread's interrupted status is cleared.
0N/A *
0N/A * <p>In this implementation, as this method is an explicit
0N/A * interruption point, preference is given to responding to
0N/A * the interrupt over normal or reentrant acquisition of the
0N/A * lock.
0N/A *
0N/A * @throws InterruptedException if the current thread is interrupted
0N/A */
0N/A public void lockInterruptibly() throws InterruptedException {
0N/A sync.acquireSharedInterruptibly(1);
0N/A }
0N/A
0N/A /**
0N/A * Acquires the read lock only if the write lock is not held by
0N/A * another thread at the time of invocation.
0N/A *
0N/A * <p>Acquires the read lock if the write lock is not held by
0N/A * another thread and returns immediately with the value
0N/A * {@code true}. Even when this lock has been set to use a
0N/A * fair ordering policy, a call to {@code tryLock()}
0N/A * <em>will</em> immediately acquire the read lock if it is
0N/A * available, whether or not other threads are currently
0N/A * waiting for the read lock. This &quot;barging&quot; behavior
0N/A * can be useful in certain circumstances, even though it
0N/A * breaks fairness. If you want to honor the fairness setting
0N/A * for this lock, then use {@link #tryLock(long, TimeUnit)
0N/A * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent
0N/A * (it also detects interruption).
0N/A *
0N/A * <p>If the write lock is held by another thread then
0N/A * this method will return immediately with the value
0N/A * {@code false}.
0N/A *
0N/A * @return {@code true} if the read lock was acquired
0N/A */
0N/A public boolean tryLock() {
0N/A return sync.tryReadLock();
0N/A }
0N/A
0N/A /**
0N/A * Acquires the read lock if the write lock is not held by
0N/A * another thread within the given waiting time and the
0N/A * current thread has not been {@linkplain Thread#interrupt
0N/A * interrupted}.
0N/A *
0N/A * <p>Acquires the read lock if the write lock is not held by
0N/A * another thread and returns immediately with the value
0N/A * {@code true}. If this lock has been set to use a fair
0N/A * ordering policy then an available lock <em>will not</em> be
0N/A * acquired if any other threads are waiting for the
0N/A * lock. This is in contrast to the {@link #tryLock()}
0N/A * method. If you want a timed {@code tryLock} that does
0N/A * permit barging on a fair lock then combine the timed and
0N/A * un-timed forms together:
0N/A *
0N/A * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
0N/A * </pre>
0N/A *
0N/A * <p>If the write lock is held by another thread then the
0N/A * current thread becomes disabled for thread scheduling
0N/A * purposes and lies dormant until one of three things happens:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>The read lock is acquired by the current thread; or
0N/A *
0N/A * <li>Some other thread {@linkplain Thread#interrupt interrupts}
0N/A * the current thread; or
0N/A *
0N/A * <li>The specified waiting time elapses.
0N/A *
0N/A * </ul>
0N/A *
0N/A * <p>If the read lock is acquired then the value {@code true} is
0N/A * returned.
0N/A *
0N/A * <p>If the current thread:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>has its interrupted status set on entry to this method; or
0N/A *
0N/A * <li>is {@linkplain Thread#interrupt interrupted} while
0N/A * acquiring the read lock,
0N/A *
0N/A * </ul> then {@link InterruptedException} is thrown and the
0N/A * current thread's interrupted status is cleared.
0N/A *
0N/A * <p>If the specified waiting time elapses then the value
0N/A * {@code false} is returned. If the time is less than or
0N/A * equal to zero, the method will not wait at all.
0N/A *
0N/A * <p>In this implementation, as this method is an explicit
0N/A * interruption point, preference is given to responding to
0N/A * the interrupt over normal or reentrant acquisition of the
0N/A * lock, and over reporting the elapse of the waiting time.
0N/A *
0N/A * @param timeout the time to wait for the read lock
0N/A * @param unit the time unit of the timeout argument
0N/A * @return {@code true} if the read lock was acquired
0N/A * @throws InterruptedException if the current thread is interrupted
0N/A * @throws NullPointerException if the time unit is null
0N/A *
0N/A */
3203N/A public boolean tryLock(long timeout, TimeUnit unit)
3203N/A throws InterruptedException {
0N/A return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
0N/A }
0N/A
0N/A /**
0N/A * Attempts to release this lock.
0N/A *
0N/A * <p> If the number of readers is now zero then the lock
0N/A * is made available for write lock attempts.
0N/A */
0N/A public void unlock() {
0N/A sync.releaseShared(1);
0N/A }
0N/A
0N/A /**
0N/A * Throws {@code UnsupportedOperationException} because
0N/A * {@code ReadLocks} do not support conditions.
0N/A *
0N/A * @throws UnsupportedOperationException always
0N/A */
0N/A public Condition newCondition() {
0N/A throw new UnsupportedOperationException();
0N/A }
0N/A
0N/A /**
0N/A * Returns a string identifying this lock, as well as its lock state.
0N/A * The state, in brackets, includes the String {@code "Read locks ="}
0N/A * followed by the number of held read locks.
0N/A *
0N/A * @return a string identifying this lock, as well as its lock state
0N/A */
0N/A public String toString() {
0N/A int r = sync.getReadLockCount();
0N/A return super.toString() +
0N/A "[Read locks = " + r + "]";
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
0N/A */
3203N/A public static class WriteLock implements Lock, java.io.Serializable {
0N/A private static final long serialVersionUID = -4992448646407690164L;
0N/A private final Sync sync;
0N/A
0N/A /**
0N/A * Constructor for use by subclasses
0N/A *
0N/A * @param lock the outer lock object
0N/A * @throws NullPointerException if the lock is null
0N/A */
0N/A protected WriteLock(ReentrantReadWriteLock lock) {
0N/A sync = lock.sync;
0N/A }
0N/A
0N/A /**
0N/A * Acquires the write lock.
0N/A *
0N/A * <p>Acquires the write lock if neither the read nor write lock
0N/A * are held by another thread
0N/A * and returns immediately, setting the write lock hold count to
0N/A * one.
0N/A *
0N/A * <p>If the current thread already holds the write lock then the
0N/A * hold count is incremented by one and the method returns
0N/A * immediately.
0N/A *
0N/A * <p>If the lock is held by another thread then the current
0N/A * thread becomes disabled for thread scheduling purposes and
0N/A * lies dormant until the write lock has been acquired, at which
0N/A * time the write lock hold count is set to one.
0N/A */
0N/A public void lock() {
0N/A sync.acquire(1);
0N/A }
0N/A
0N/A /**
0N/A * Acquires the write lock unless the current thread is
0N/A * {@linkplain Thread#interrupt interrupted}.
0N/A *
0N/A * <p>Acquires the write lock if neither the read nor write lock
0N/A * are held by another thread
0N/A * and returns immediately, setting the write lock hold count to
0N/A * one.
0N/A *
0N/A * <p>If the current thread already holds this lock then the
0N/A * hold count is incremented by one and the method returns
0N/A * immediately.
0N/A *
0N/A * <p>If the lock is held by another thread then the current
0N/A * thread becomes disabled for thread scheduling purposes and
0N/A * lies dormant until one of two things happens:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>The write lock is acquired by the current thread; or
0N/A *
0N/A * <li>Some other thread {@linkplain Thread#interrupt interrupts}
0N/A * the current thread.
0N/A *
0N/A * </ul>
0N/A *
0N/A * <p>If the write lock is acquired by the current thread then the
0N/A * lock hold count is set to one.
0N/A *
0N/A * <p>If the current thread:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>has its interrupted status set on entry to this method;
0N/A * or
0N/A *
0N/A * <li>is {@linkplain Thread#interrupt interrupted} while
0N/A * acquiring the write lock,
0N/A *
0N/A * </ul>
0N/A *
0N/A * then {@link InterruptedException} is thrown and the current
0N/A * thread's interrupted status is cleared.
0N/A *
0N/A * <p>In this implementation, as this method is an explicit
0N/A * interruption point, preference is given to responding to
0N/A * the interrupt over normal or reentrant acquisition of the
0N/A * lock.
0N/A *
0N/A * @throws InterruptedException if the current thread is interrupted
0N/A */
0N/A public void lockInterruptibly() throws InterruptedException {
0N/A sync.acquireInterruptibly(1);
0N/A }
0N/A
0N/A /**
0N/A * Acquires the write lock only if it is not held by another thread
0N/A * at the time of invocation.
0N/A *
0N/A * <p>Acquires the write lock if neither the read nor write lock
0N/A * are held by another thread
0N/A * and returns immediately with the value {@code true},
0N/A * setting the write lock hold count to one. Even when this lock has
0N/A * been set to use a fair ordering policy, a call to
0N/A * {@code tryLock()} <em>will</em> immediately acquire the
0N/A * lock if it is available, whether or not other threads are
0N/A * currently waiting for the write lock. This &quot;barging&quot;
0N/A * behavior can be useful in certain circumstances, even
0N/A * though it breaks fairness. If you want to honor the
0N/A * fairness setting for this lock, then use {@link
0N/A * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
0N/A * which is almost equivalent (it also detects interruption).
0N/A *
0N/A * <p> If the current thread already holds this lock then the
0N/A * hold count is incremented by one and the method returns
0N/A * {@code true}.
0N/A *
0N/A * <p>If the lock is held by another thread then this method
0N/A * will return immediately with the value {@code false}.
0N/A *
0N/A * @return {@code true} if the lock was free and was acquired
0N/A * by the current thread, or the write lock was already held
0N/A * by the current thread; and {@code false} otherwise.
0N/A */
0N/A public boolean tryLock( ) {
0N/A return sync.tryWriteLock();
0N/A }
0N/A
0N/A /**
0N/A * Acquires the write lock if it is not held by another thread
0N/A * within the given waiting time and the current thread has
0N/A * not been {@linkplain Thread#interrupt interrupted}.
0N/A *
0N/A * <p>Acquires the write lock if neither the read nor write lock
0N/A * are held by another thread
0N/A * and returns immediately with the value {@code true},
0N/A * setting the write lock hold count to one. If this lock has been
0N/A * set to use a fair ordering policy then an available lock
0N/A * <em>will not</em> be acquired if any other threads are
0N/A * waiting for the write lock. This is in contrast to the {@link
0N/A * #tryLock()} method. If you want a timed {@code tryLock}
0N/A * that does permit barging on a fair lock then combine the
0N/A * timed and un-timed forms together:
0N/A *
0N/A * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
0N/A * </pre>
0N/A *
0N/A * <p>If the current thread already holds this lock then the
0N/A * hold count is incremented by one and the method returns
0N/A * {@code true}.
0N/A *
0N/A * <p>If the lock is held by another thread then the current
0N/A * thread becomes disabled for thread scheduling purposes and
0N/A * lies dormant until one of three things happens:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>The write lock is acquired by the current thread; or
0N/A *
0N/A * <li>Some other thread {@linkplain Thread#interrupt interrupts}
0N/A * the current thread; or
0N/A *
0N/A * <li>The specified waiting time elapses
0N/A *
0N/A * </ul>
0N/A *
0N/A * <p>If the write lock is acquired then the value {@code true} is
0N/A * returned and the write lock hold count is set to one.
0N/A *
0N/A * <p>If the current thread:
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>has its interrupted status set on entry to this method;
0N/A * or
0N/A *
0N/A * <li>is {@linkplain Thread#interrupt interrupted} while
0N/A * acquiring the write lock,
0N/A *
0N/A * </ul>
0N/A *
0N/A * then {@link InterruptedException} is thrown and the current
0N/A * thread's interrupted status is cleared.
0N/A *
0N/A * <p>If the specified waiting time elapses then the value
0N/A * {@code false} is returned. If the time is less than or
0N/A * equal to zero, the method will not wait at all.
0N/A *
0N/A * <p>In this implementation, as this method is an explicit
0N/A * interruption point, preference is given to responding to
0N/A * the interrupt over normal or reentrant acquisition of the
0N/A * lock, and over reporting the elapse of the waiting time.
0N/A *
0N/A * @param timeout the time to wait for the write lock
0N/A * @param unit the time unit of the timeout argument
0N/A *
0N/A * @return {@code true} if the lock was free and was acquired
0N/A * by the current thread, or the write lock was already held by the
0N/A * current thread; and {@code false} if the waiting time
0N/A * elapsed before the lock could be acquired.
0N/A *
0N/A * @throws InterruptedException if the current thread is interrupted
0N/A * @throws NullPointerException if the time unit is null
0N/A *
0N/A */
3203N/A public boolean tryLock(long timeout, TimeUnit unit)
3203N/A throws InterruptedException {
0N/A return sync.tryAcquireNanos(1, unit.toNanos(timeout));
0N/A }
0N/A
0N/A /**
0N/A * Attempts to release this lock.
0N/A *
0N/A * <p>If the current thread is the holder of this lock then
0N/A * the hold count is decremented. If the hold count is now
0N/A * zero then the lock is released. If the current thread is
0N/A * not the holder of this lock then {@link
0N/A * IllegalMonitorStateException} is thrown.
0N/A *
0N/A * @throws IllegalMonitorStateException if the current thread does not
0N/A * hold this lock.
0N/A */
0N/A public void unlock() {
0N/A sync.release(1);
0N/A }
0N/A
0N/A /**
0N/A * Returns a {@link Condition} instance for use with this
0N/A * {@link Lock} instance.
0N/A * <p>The returned {@link Condition} instance supports the same
0N/A * usages as do the {@link Object} monitor methods ({@link
0N/A * Object#wait() wait}, {@link Object#notify notify}, and {@link
0N/A * Object#notifyAll notifyAll}) when used with the built-in
0N/A * monitor lock.
0N/A *
0N/A * <ul>
0N/A *
0N/A * <li>If this write lock is not held when any {@link
0N/A * Condition} method is called then an {@link
0N/A * IllegalMonitorStateException} is thrown. (Read locks are
0N/A * held independently of write locks, so are not checked or
0N/A * affected. However it is essentially always an error to
0N/A * invoke a condition waiting method when the current thread
0N/A * has also acquired read locks, since other threads that
0N/A * could unblock it will not be able to acquire the write
0N/A * lock.)
0N/A *
0N/A * <li>When the condition {@linkplain Condition#await() waiting}
0N/A * methods are called the write lock is released and, before
0N/A * they return, the write lock is reacquired and the lock hold
0N/A * count restored to what it was when the method was called.
0N/A *
0N/A * <li>If a thread is {@linkplain Thread#interrupt interrupted} while
0N/A * waiting then the wait will terminate, an {@link
0N/A * InterruptedException} will be thrown, and the thread's
0N/A * interrupted status will be cleared.
0N/A *
0N/A * <li> Waiting threads are signalled in FIFO order.
0N/A *
0N/A * <li>The ordering of lock reacquisition for threads returning
0N/A * from waiting methods is the same as for threads initially
0N/A * acquiring the lock, which is in the default case not specified,
0N/A * but for <em>fair</em> locks favors those threads that have been
0N/A * waiting the longest.
0N/A *
0N/A * </ul>
0N/A *
0N/A * @return the Condition object
0N/A */
0N/A public Condition newCondition() {
0N/A return sync.newCondition();
0N/A }
0N/A
0N/A /**
0N/A * Returns a string identifying this lock, as well as its lock
0N/A * state. The state, in brackets includes either the String
0N/A * {@code "Unlocked"} or the String {@code "Locked by"}
0N/A * followed by the {@linkplain Thread#getName name} of the owning thread.
0N/A *
0N/A * @return a string identifying this lock, as well as its lock state
0N/A */
0N/A public String toString() {
0N/A Thread o = sync.getOwner();
0N/A return super.toString() + ((o == null) ?
0N/A "[Unlocked]" :
0N/A "[Locked by thread " + o.getName() + "]");
0N/A }
0N/A
0N/A /**
0N/A * Queries if this write lock is held by the current thread.
0N/A * Identical in effect to {@link
0N/A * ReentrantReadWriteLock#isWriteLockedByCurrentThread}.
0N/A *
0N/A * @return {@code true} if the current thread holds this lock and
0N/A * {@code false} otherwise
0N/A * @since 1.6
0N/A */
0N/A public boolean isHeldByCurrentThread() {
0N/A return sync.isHeldExclusively();
0N/A }
0N/A
0N/A /**
0N/A * Queries the number of holds on this write lock by the current
0N/A * thread. A thread has a hold on a lock for each lock action
0N/A * that is not matched by an unlock action. Identical in effect
0N/A * to {@link ReentrantReadWriteLock#getWriteHoldCount}.
0N/A *
0N/A * @return the number of holds on this lock by the current thread,
0N/A * or zero if this lock is not held by the current thread
0N/A * @since 1.6
0N/A */
0N/A public int getHoldCount() {
0N/A return sync.getWriteHoldCount();
0N/A }
0N/A }
0N/A
0N/A // Instrumentation and status
0N/A
0N/A /**
0N/A * Returns {@code true} if this lock has fairness set true.
0N/A *
0N/A * @return {@code true} if this lock has fairness set true
0N/A */
0N/A public final boolean isFair() {
0N/A return sync instanceof FairSync;
0N/A }
0N/A
0N/A /**
0N/A * Returns the thread that currently owns the write lock, or
0N/A * {@code null} if not owned. When this method is called by a
0N/A * thread that is not the owner, the return value reflects a
0N/A * best-effort approximation of current lock status. For example,
0N/A * the owner may be momentarily {@code null} even if there are
0N/A * threads trying to acquire the lock but have not yet done so.
0N/A * This method is designed to facilitate construction of
0N/A * subclasses that provide more extensive lock monitoring
0N/A * facilities.
0N/A *
0N/A * @return the owner, or {@code null} if not owned
0N/A */
0N/A protected Thread getOwner() {
0N/A return sync.getOwner();
0N/A }
0N/A
0N/A /**
0N/A * Queries the number of read locks held for this lock. This
0N/A * method is designed for use in monitoring system state, not for
0N/A * synchronization control.
0N/A * @return the number of read locks held.
0N/A */
0N/A public int getReadLockCount() {
0N/A return sync.getReadLockCount();
0N/A }
0N/A
0N/A /**
0N/A * Queries if the write lock is held by any thread. This method is
0N/A * designed for use in monitoring system state, not for
0N/A * synchronization control.
0N/A *
0N/A * @return {@code true} if any thread holds the write lock and
0N/A * {@code false} otherwise
0N/A */
0N/A public boolean isWriteLocked() {
0N/A return sync.isWriteLocked();
0N/A }
0N/A
0N/A /**
0N/A * Queries if the write lock is held by the current thread.
0N/A *
0N/A * @return {@code true} if the current thread holds the write lock and
0N/A * {@code false} otherwise
0N/A */
0N/A public boolean isWriteLockedByCurrentThread() {
0N/A return sync.isHeldExclusively();
0N/A }
0N/A
0N/A /**
0N/A * Queries the number of reentrant write holds on this lock by the
0N/A * current thread. A writer thread has a hold on a lock for
0N/A * each lock action that is not matched by an unlock action.
0N/A *
0N/A * @return the number of holds on the write lock by the current thread,
0N/A * or zero if the write lock is not held by the current thread
0N/A */
0N/A public int getWriteHoldCount() {
0N/A return sync.getWriteHoldCount();
0N/A }
0N/A
0N/A /**
0N/A * Queries the number of reentrant read holds on this lock by the
0N/A * current thread. A reader thread has a hold on a lock for
0N/A * each lock action that is not matched by an unlock action.
0N/A *
0N/A * @return the number of holds on the read lock by the current thread,
0N/A * or zero if the read lock is not held by the current thread
0N/A * @since 1.6
0N/A */
0N/A public int getReadHoldCount() {
0N/A return sync.getReadHoldCount();
0N/A }
0N/A
0N/A /**
0N/A * Returns a collection containing threads that may be waiting to
0N/A * acquire the write lock. Because the actual set of threads may
0N/A * change dynamically while constructing this result, the returned
0N/A * collection is only a best-effort estimate. The elements of the
0N/A * returned collection are in no particular order. This method is
0N/A * designed to facilitate construction of subclasses that provide
0N/A * more extensive lock monitoring facilities.
0N/A *
0N/A * @return the collection of threads
0N/A */
0N/A protected Collection<Thread> getQueuedWriterThreads() {
0N/A return sync.getExclusiveQueuedThreads();
0N/A }
0N/A
0N/A /**
0N/A * Returns a collection containing threads that may be waiting to
0N/A * acquire the read lock. Because the actual set of threads may
0N/A * change dynamically while constructing this result, the returned
0N/A * collection is only a best-effort estimate. The elements of the
0N/A * returned collection are in no particular order. This method is
0N/A * designed to facilitate construction of subclasses that provide
0N/A * more extensive lock monitoring facilities.
0N/A *
0N/A * @return the collection of threads
0N/A */
0N/A protected Collection<Thread> getQueuedReaderThreads() {
0N/A return sync.getSharedQueuedThreads();
0N/A }
0N/A
0N/A /**
0N/A * Queries whether any threads are waiting to acquire the read or
0N/A * write lock. Note that because cancellations may occur at any
0N/A * time, a {@code true} return does not guarantee that any other
0N/A * thread will ever acquire a lock. This method is designed
0N/A * primarily for use in monitoring of the system state.
0N/A *
0N/A * @return {@code true} if there may be other threads waiting to
0N/A * acquire the lock
0N/A */
0N/A public final boolean hasQueuedThreads() {
0N/A return sync.hasQueuedThreads();
0N/A }
0N/A
0N/A /**
0N/A * Queries whether the given thread is waiting to acquire either
0N/A * the read or write lock. Note that because cancellations may
0N/A * occur at any time, a {@code true} return does not guarantee
0N/A * that this thread will ever acquire a lock. This method is
0N/A * designed primarily for use in monitoring of the system state.
0N/A *
0N/A * @param thread the thread
0N/A * @return {@code true} if the given thread is queued waiting for this lock
0N/A * @throws NullPointerException if the thread is null
0N/A */
0N/A public final boolean hasQueuedThread(Thread thread) {
0N/A return sync.isQueued(thread);
0N/A }
0N/A
0N/A /**
0N/A * Returns an estimate of the number of threads waiting to acquire
0N/A * either the read or write lock. The value is only an estimate
0N/A * because the number of threads may change dynamically while this
0N/A * method traverses internal data structures. This method is
0N/A * designed for use in monitoring of the system state, not for
0N/A * synchronization control.
0N/A *
0N/A * @return the estimated number of threads waiting for this lock
0N/A */
0N/A public final int getQueueLength() {
0N/A return sync.getQueueLength();
0N/A }
0N/A
0N/A /**
0N/A * Returns a collection containing threads that may be waiting to
0N/A * acquire either the read or write lock. Because the actual set
0N/A * of threads may change dynamically while constructing this
0N/A * result, the returned collection is only a best-effort estimate.
0N/A * The elements of the returned collection are in no particular
0N/A * order. This method is designed to facilitate construction of
0N/A * subclasses that provide more extensive monitoring facilities.
0N/A *
0N/A * @return the collection of threads
0N/A */
0N/A protected Collection<Thread> getQueuedThreads() {
0N/A return sync.getQueuedThreads();
0N/A }
0N/A
0N/A /**
0N/A * Queries whether any threads are waiting on the given condition
0N/A * associated with the write lock. Note that because timeouts and
0N/A * interrupts may occur at any time, a {@code true} return does
0N/A * not guarantee that a future {@code signal} will awaken any
0N/A * threads. This method is designed primarily for use in
0N/A * monitoring of the system state.
0N/A *
0N/A * @param condition the condition
0N/A * @return {@code true} if there are any waiting threads
0N/A * @throws IllegalMonitorStateException if this lock is not held
0N/A * @throws IllegalArgumentException if the given condition is
0N/A * not associated with this lock
0N/A * @throws NullPointerException if the condition is null
0N/A */
0N/A public boolean hasWaiters(Condition condition) {
0N/A if (condition == null)
0N/A throw new NullPointerException();
0N/A if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
0N/A throw new IllegalArgumentException("not owner");
0N/A return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
0N/A }
0N/A
0N/A /**
0N/A * Returns an estimate of the number of threads waiting on the
0N/A * given condition associated with the write lock. Note that because
0N/A * timeouts and interrupts may occur at any time, the estimate
0N/A * serves only as an upper bound on the actual number of waiters.
0N/A * This method is designed for use in monitoring of the system
0N/A * state, not for synchronization control.
0N/A *
0N/A * @param condition the condition
0N/A * @return the estimated number of waiting threads
0N/A * @throws IllegalMonitorStateException if this lock is not held
0N/A * @throws IllegalArgumentException if the given condition is
0N/A * not associated with this lock
0N/A * @throws NullPointerException if the condition is null
0N/A */
0N/A public int getWaitQueueLength(Condition condition) {
0N/A if (condition == null)
0N/A throw new NullPointerException();
0N/A if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
0N/A throw new IllegalArgumentException("not owner");
0N/A return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
0N/A }
0N/A
0N/A /**
0N/A * Returns a collection containing those threads that may be
0N/A * waiting on the given condition associated with the write lock.
0N/A * Because the actual set of threads may change dynamically while
0N/A * constructing this result, the returned collection is only a
0N/A * best-effort estimate. The elements of the returned collection
0N/A * are in no particular order. This method is designed to
0N/A * facilitate construction of subclasses that provide more
0N/A * extensive condition monitoring facilities.
0N/A *
0N/A * @param condition the condition
0N/A * @return the collection of threads
0N/A * @throws IllegalMonitorStateException if this lock is not held
0N/A * @throws IllegalArgumentException if the given condition is
0N/A * not associated with this lock
0N/A * @throws NullPointerException if the condition is null
0N/A */
0N/A protected Collection<Thread> getWaitingThreads(Condition condition) {
0N/A if (condition == null)
0N/A throw new NullPointerException();
0N/A if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
0N/A throw new IllegalArgumentException("not owner");
0N/A return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
0N/A }
0N/A
0N/A /**
0N/A * Returns a string identifying this lock, as well as its lock state.
0N/A * The state, in brackets, includes the String {@code "Write locks ="}
0N/A * followed by the number of reentrantly held write locks, and the
0N/A * String {@code "Read locks ="} followed by the number of held
0N/A * read locks.
0N/A *
0N/A * @return a string identifying this lock, as well as its lock state
0N/A */
0N/A public String toString() {
0N/A int c = sync.getCount();
0N/A int w = Sync.exclusiveCount(c);
0N/A int r = Sync.sharedCount(c);
0N/A
0N/A return super.toString() +
0N/A "[Write locks = " + w + ", Read locks = " + r + "]";
0N/A }
0N/A
0N/A}