2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
7 package java.util.concurrent.locks;
9 import java.util.Collection;
10 import java.util.concurrent.TimeUnit;
13 * An implementation of {@link ReadWriteLock} supporting similar
14 * semantics to {@link ReentrantLock}.
15 * <p>This class has the following properties:
18 * <li><b>Acquisition order</b>
20 * <p> This class does not impose a reader or writer preference
21 * ordering for lock access. However, it does support an optional
22 * <em>fairness</em> policy.
25 * <dt><b><i>Non-fair mode (default)</i></b>
26 * <dd>When constructed as non-fair (the default), the order of entry
27 * to the read and write lock is unspecified, subject to reentrancy
28 * constraints. A nonfair lock that is continuously contended may
29 * indefinitely postpone one or more reader or writer threads, but
30 * will normally have higher throughput than a fair lock.
33 * <dt><b><i>Fair mode</i></b>
34 * <dd> When constructed as fair, threads contend for entry using an
35 * approximately arrival-order policy. When the currently held lock
36 * is released either the longest-waiting single writer thread will
37 * be assigned the write lock, or if there is a group of reader threads
38 * waiting longer than all waiting writer threads, that group will be
39 * assigned the read lock.
41 * <p>A thread that tries to acquire a fair read lock (non-reentrantly)
42 * will block if either the write lock is held, or there is a waiting
43 * writer thread. The thread will not acquire the read lock until
44 * after the oldest currently waiting writer thread has acquired and
45 * released the write lock. Of course, if a waiting writer abandons
46 * its wait, leaving one or more reader threads as the longest waiters
47 * in the queue with the write lock free, then those readers will be
48 * assigned the read lock.
50 * <p>A thread that tries to acquire a fair write lock (non-reentrantly)
51 * will block unless both the read lock and write lock are free (which
52 * implies there are no waiting threads). (Note that the non-blocking
53 * {@link ReadLock#tryLock()} and {@link WriteLock#tryLock()} methods
54 * do not honor this fair setting and will acquire the lock if it is
55 * possible, regardless of waiting threads.)
59 * <li><b>Reentrancy</b>
61 * <p>This lock allows both readers and writers to reacquire read or
62 * write locks in the style of a {@link ReentrantLock}. Non-reentrant
63 * readers are not allowed until all write locks held by the writing
64 * thread have been released.
66 * <p>Additionally, a writer can acquire the read lock, but not
67 * vice-versa. Among other applications, reentrancy can be useful
68 * when write locks are held during calls or callbacks to methods that
69 * perform reads under read locks. If a reader tries to acquire the
70 * write lock it will never succeed.
72 * <li><b>Lock downgrading</b>
73 * <p>Reentrancy also allows downgrading from the write lock to a read lock,
74 * by acquiring the write lock, then the read lock and then releasing the
75 * write lock. However, upgrading from a read lock to the write lock is
76 * <b>not</b> possible.
78 * <li><b>Interruption of lock acquisition</b>
79 * <p>The read lock and write lock both support interruption during lock
82 * <li><b>{@link Condition} support</b>
83 * <p>The write lock provides a {@link Condition} implementation that
84 * behaves in the same way, with respect to the write lock, as the
85 * {@link Condition} implementation provided by
86 * {@link ReentrantLock#newCondition} does for {@link ReentrantLock}.
87 * This {@link Condition} can, of course, only be used with the write lock.
89 * <p>The read lock does not support a {@link Condition} and
90 * {@code readLock().newCondition()} throws
91 * {@code UnsupportedOperationException}.
93 * <li><b>Instrumentation</b>
94 * <p>This class supports methods to determine whether locks
95 * are held or contended. These methods are designed for monitoring
96 * system state, not for synchronization control.
99 * <p>Serialization of this class behaves in the same way as built-in
100 * locks: a deserialized lock is in the unlocked state, regardless of
101 * its state when serialized.
103 * <p><b>Sample usages</b>. Here is a code sketch showing how to perform
104 * lock downgrading after updating a cache (exception handling is
105 * particularly tricky when handling multiple locks in a non-nested
111 * volatile boolean cacheValid;
112 * final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
114 * void processCachedData() {
115 * rwl.readLock().lock();
117 * // Must release read lock before acquiring write lock
118 * rwl.readLock().unlock();
119 * rwl.writeLock().lock();
121 * // Recheck state because another thread might have
122 * // acquired write lock and changed state before we did.
127 * // Downgrade by acquiring read lock before releasing write lock
128 * rwl.readLock().lock();
130 * rwl.writeLock().unlock(); // Unlock write, still hold read
137 * rwl.readLock().unlock();
142 * ReentrantReadWriteLocks can be used to improve concurrency in some
143 * uses of some kinds of Collections. This is typically worthwhile
144 * only when the collections are expected to be large, accessed by
145 * more reader threads than writer threads, and entail operations with
146 * overhead that outweighs synchronization overhead. For example, here
147 * is a class using a TreeMap that is expected to be large and
148 * concurrently accessed.
151 * class RWDictionary {
152 * private final Map<String, Data> m = new TreeMap<String, Data>();
153 * private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
154 * private final Lock r = rwl.readLock();
155 * private final Lock w = rwl.writeLock();
157 * public Data get(String key) {
159 * try { return m.get(key); }
160 * finally { r.unlock(); }
162 * public String[] allKeys() {
164 * try { return m.keySet().toArray(); }
165 * finally { r.unlock(); }
167 * public Data put(String key, Data value) {
169 * try { return m.put(key, value); }
170 * finally { w.unlock(); }
172 * public void clear() {
175 * finally { w.unlock(); }
179 * <h3>Implementation Notes</h3>
181 * <p>This lock supports a maximum of 65535 recursive write locks
182 * and 65535 read locks. Attempts to exceed these limits result in
183 * {@link Error} throws from locking methods.
189 public class ReentrantReadWriteLock implements ReadWriteLock, java.io.Serializable {
190 private static final long serialVersionUID = -6992448646407690164L;
191 /** Inner class providing readlock */
192 private final ReentrantReadWriteLock.ReadLock readerLock;
193 /** Inner class providing writelock */
194 private final ReentrantReadWriteLock.WriteLock writerLock;
195 /** Performs all synchronization mechanics */
199 * Creates a new {@code ReentrantReadWriteLock} with
200 * default (nonfair) ordering properties.
202 public ReentrantReadWriteLock() {
207 * Creates a new {@code ReentrantReadWriteLock} with
208 * the given fairness policy.
210 * @param fair {@code true} if this lock should use a fair ordering policy
212 public ReentrantReadWriteLock(boolean fair) {
213 sync = fair ? new FairSync() : new NonfairSync();
214 readerLock = new ReadLock(this);
215 writerLock = new WriteLock(this);
218 public ReentrantReadWriteLock.WriteLock writeLock() { return writerLock; }
219 public ReentrantReadWriteLock.ReadLock readLock() { return readerLock; }
222 * Synchronization implementation for ReentrantReadWriteLock.
223 * Subclassed into fair and nonfair versions.
225 static abstract class Sync extends AbstractQueuedSynchronizer {
226 private static final long serialVersionUID = 6317671515068378041L;
229 * Read vs write count extraction constants and functions.
230 * Lock state is logically divided into two unsigned shorts:
231 * The lower one representing the exclusive (writer) lock hold count,
232 * and the upper the shared (reader) hold count.
235 static final int SHARED_SHIFT = 16;
236 static final int SHARED_UNIT = (1 << SHARED_SHIFT);
237 static final int MAX_COUNT = (1 << SHARED_SHIFT) - 1;
238 static final int EXCLUSIVE_MASK = (1 << SHARED_SHIFT) - 1;
240 /** Returns the number of shared holds represented in count */
241 static int sharedCount(int c) { return c >>> SHARED_SHIFT; }
242 /** Returns the number of exclusive holds represented in count */
243 static int exclusiveCount(int c) { return c & EXCLUSIVE_MASK; }
246 * A counter for per-thread read hold counts.
247 * Maintained as a ThreadLocal; cached in cachedHoldCounter
249 static final class HoldCounter {
251 // Use id, not reference, to avoid garbage retention
252 final long tid = Thread.currentThread().getId();
256 * ThreadLocal subclass. Easiest to explicitly define for sake
257 * of deserialization mechanics.
259 static final class ThreadLocalHoldCounter
260 extends ThreadLocal<HoldCounter> {
261 public HoldCounter initialValue() {
262 return new HoldCounter();
267 * The number of reentrant read locks held by current thread.
268 * Initialized only in constructor and readObject.
269 * Removed whenever a thread's read hold count drops to 0.
271 private transient ThreadLocalHoldCounter readHolds;
274 * The hold count of the last thread to successfully acquire
275 * readLock. This saves ThreadLocal lookup in the common case
276 * where the next thread to release is the last one to
277 * acquire. This is non-volatile since it is just used
278 * as a heuristic, and would be great for threads to cache.
280 * <p>Can outlive the Thread for which it is caching the read
281 * hold count, but avoids garbage retention by not retaining a
282 * reference to the Thread.
284 * <p>Accessed via a benign data race; relies on the memory
285 * model's final field and out-of-thin-air guarantees.
287 private transient HoldCounter cachedHoldCounter;
290 * firstReader is the first thread to have acquired the read lock.
291 * firstReaderHoldCount is firstReader's hold count.
293 * <p>More precisely, firstReader is the unique thread that last
294 * changed the shared count from 0 to 1, and has not released the
295 * read lock since then; null if there is no such thread.
297 * <p>Cannot cause garbage retention unless the thread terminated
298 * without relinquishing its read locks, since tryReleaseShared
301 * <p>Accessed via a benign data race; relies on the memory
302 * model's out-of-thin-air guarantees for references.
304 * <p>This allows tracking of read holds for uncontended read
305 * locks to be very cheap.
307 private transient Thread firstReader = null;
308 private transient int firstReaderHoldCount;
311 readHolds = new ThreadLocalHoldCounter();
312 setState(getState()); // ensures visibility of readHolds
316 * Acquires and releases use the same code for fair and
317 * nonfair locks, but differ in whether/how they allow barging
318 * when queues are non-empty.
322 * Returns true if the current thread, when trying to acquire
323 * the read lock, and otherwise eligible to do so, should block
324 * because of policy for overtaking other waiting threads.
326 abstract boolean readerShouldBlock();
329 * Returns true if the current thread, when trying to acquire
330 * the write lock, and otherwise eligible to do so, should block
331 * because of policy for overtaking other waiting threads.
333 abstract boolean writerShouldBlock();
336 * Note that tryRelease and tryAcquire can be called by
337 * Conditions. So it is possible that their arguments contain
338 * both read and write holds that are all released during a
339 * condition wait and re-established in tryAcquire.
342 protected final boolean tryRelease(int releases) {
343 if (!isHeldExclusively())
344 throw new IllegalMonitorStateException();
345 int nextc = getState() - releases;
346 boolean free = exclusiveCount(nextc) == 0;
348 setExclusiveOwnerThread(null);
353 protected final boolean tryAcquire(int acquires) {
356 * 1. If read count nonzero or write count nonzero
357 * and owner is a different thread, fail.
358 * 2. If count would saturate, fail. (This can only
359 * happen if count is already nonzero.)
360 * 3. Otherwise, this thread is eligible for lock if
361 * it is either a reentrant acquire or
362 * queue policy allows it. If so, update state
365 Thread current = Thread.currentThread();
367 int w = exclusiveCount(c);
369 // (Note: if c != 0 and w == 0 then shared count != 0)
370 if (w == 0 || current != getExclusiveOwnerThread())
372 if (w + exclusiveCount(acquires) > MAX_COUNT)
373 throw new Error("Maximum lock count exceeded");
375 setState(c + acquires);
378 if (writerShouldBlock() ||
379 !compareAndSetState(c, c + acquires))
381 setExclusiveOwnerThread(current);
385 protected final boolean tryReleaseShared(int unused) {
386 Thread current = Thread.currentThread();
387 if (firstReader == current) {
388 // assert firstReaderHoldCount > 0;
389 if (firstReaderHoldCount == 1)
392 firstReaderHoldCount--;
394 HoldCounter rh = cachedHoldCounter;
395 if (rh == null || rh.tid != current.getId())
396 rh = readHolds.get();
397 int count = rh.count;
401 throw unmatchedUnlockException();
407 int nextc = c - SHARED_UNIT;
408 if (compareAndSetState(c, nextc))
409 // Releasing the read lock has no effect on readers,
410 // but it may allow waiting writers to proceed if
411 // both read and write locks are now free.
416 private IllegalMonitorStateException unmatchedUnlockException() {
417 return new IllegalMonitorStateException(
418 "attempt to unlock read lock, not locked by current thread");
421 protected final int tryAcquireShared(int unused) {
424 * 1. If write lock held by another thread, fail.
425 * 2. Otherwise, this thread is eligible for
426 * lock wrt state, so ask if it should block
427 * because of queue policy. If not, try
428 * to grant by CASing state and updating count.
429 * Note that step does not check for reentrant
430 * acquires, which is postponed to full version
431 * to avoid having to check hold count in
432 * the more typical non-reentrant case.
433 * 3. If step 2 fails either because thread
434 * apparently not eligible or CAS fails or count
435 * saturated, chain to version with full retry loop.
437 Thread current = Thread.currentThread();
439 if (exclusiveCount(c) != 0 &&
440 getExclusiveOwnerThread() != current)
442 int r = sharedCount(c);
443 if (!readerShouldBlock() &&
445 compareAndSetState(c, c + SHARED_UNIT)) {
447 firstReader = current;
448 firstReaderHoldCount = 1;
449 } else if (firstReader == current) {
450 firstReaderHoldCount++;
452 HoldCounter rh = cachedHoldCounter;
453 if (rh == null || rh.tid != current.getId())
454 cachedHoldCounter = rh = readHolds.get();
455 else if (rh.count == 0)
461 return fullTryAcquireShared(current);
465 * Full version of acquire for reads, that handles CAS misses
466 * and reentrant reads not dealt with in tryAcquireShared.
468 final int fullTryAcquireShared(Thread current) {
470 * This code is in part redundant with that in
471 * tryAcquireShared but is simpler overall by not
472 * complicating tryAcquireShared with interactions between
473 * retries and lazily reading hold counts.
475 HoldCounter rh = null;
478 if (exclusiveCount(c) != 0) {
479 if (getExclusiveOwnerThread() != current)
481 // else we hold the exclusive lock; blocking here
482 // would cause deadlock.
483 } else if (readerShouldBlock()) {
484 // Make sure we're not acquiring read lock reentrantly
485 if (firstReader == current) {
486 // assert firstReaderHoldCount > 0;
489 rh = cachedHoldCounter;
490 if (rh == null || rh.tid != current.getId()) {
491 rh = readHolds.get();
500 if (sharedCount(c) == MAX_COUNT)
501 throw new Error("Maximum lock count exceeded");
502 if (compareAndSetState(c, c + SHARED_UNIT)) {
503 if (sharedCount(c) == 0) {
504 firstReader = current;
505 firstReaderHoldCount = 1;
506 } else if (firstReader == current) {
507 firstReaderHoldCount++;
510 rh = cachedHoldCounter;
511 if (rh == null || rh.tid != current.getId())
512 rh = readHolds.get();
513 else if (rh.count == 0)
516 cachedHoldCounter = rh; // cache for release
524 * Performs tryLock for write, enabling barging in both modes.
525 * This is identical in effect to tryAcquire except for lack
526 * of calls to writerShouldBlock.
528 final boolean tryWriteLock() {
529 Thread current = Thread.currentThread();
532 int w = exclusiveCount(c);
533 if (w == 0 || current != getExclusiveOwnerThread())
536 throw new Error("Maximum lock count exceeded");
538 if (!compareAndSetState(c, c + 1))
540 setExclusiveOwnerThread(current);
545 * Performs tryLock for read, enabling barging in both modes.
546 * This is identical in effect to tryAcquireShared except for
547 * lack of calls to readerShouldBlock.
549 final boolean tryReadLock() {
550 Thread current = Thread.currentThread();
553 if (exclusiveCount(c) != 0 &&
554 getExclusiveOwnerThread() != current)
556 int r = sharedCount(c);
558 throw new Error("Maximum lock count exceeded");
559 if (compareAndSetState(c, c + SHARED_UNIT)) {
561 firstReader = current;
562 firstReaderHoldCount = 1;
563 } else if (firstReader == current) {
564 firstReaderHoldCount++;
566 HoldCounter rh = cachedHoldCounter;
567 if (rh == null || rh.tid != current.getId())
568 cachedHoldCounter = rh = readHolds.get();
569 else if (rh.count == 0)
578 protected final boolean isHeldExclusively() {
579 // While we must in general read state before owner,
580 // we don't need to do so to check if current thread is owner
581 return getExclusiveOwnerThread() == Thread.currentThread();
584 // Methods relayed to outer class
586 final ConditionObject newCondition() {
587 return new ConditionObject();
590 final Thread getOwner() {
591 // Must read state before owner to ensure memory consistency
592 return ((exclusiveCount(getState()) == 0)?
594 getExclusiveOwnerThread());
597 final int getReadLockCount() {
598 return sharedCount(getState());
601 final boolean isWriteLocked() {
602 return exclusiveCount(getState()) != 0;
605 final int getWriteHoldCount() {
606 return isHeldExclusively() ? exclusiveCount(getState()) : 0;
609 final int getReadHoldCount() {
610 if (getReadLockCount() == 0)
613 Thread current = Thread.currentThread();
614 if (firstReader == current)
615 return firstReaderHoldCount;
617 HoldCounter rh = cachedHoldCounter;
618 if (rh != null && rh.tid == current.getId())
621 int count = readHolds.get().count;
622 if (count == 0) readHolds.remove();
627 * Reconstitute this lock instance from a stream
628 * @param s the stream
630 private void readObject(java.io.ObjectInputStream s)
631 throws java.io.IOException, ClassNotFoundException {
632 s.defaultReadObject();
633 readHolds = new ThreadLocalHoldCounter();
634 setState(0); // reset to unlocked state
637 final int getCount() { return getState(); }
641 * Nonfair version of Sync
643 final static class NonfairSync extends Sync {
644 private static final long serialVersionUID = -8159625535654395037L;
645 final boolean writerShouldBlock() {
646 return false; // writers can always barge
648 final boolean readerShouldBlock() {
649 /* As a heuristic to avoid indefinite writer starvation,
650 * block if the thread that momentarily appears to be head
651 * of queue, if one exists, is a waiting writer. This is
652 * only a probabilistic effect since a new reader will not
653 * block if there is a waiting writer behind other enabled
654 * readers that have not yet drained from the queue.
656 return apparentlyFirstQueuedIsExclusive();
661 * Fair version of Sync
663 final static class FairSync extends Sync {
664 private static final long serialVersionUID = -2274990926593161451L;
665 final boolean writerShouldBlock() {
666 return hasQueuedPredecessors();
668 final boolean readerShouldBlock() {
669 return hasQueuedPredecessors();
674 * The lock returned by method {@link ReentrantReadWriteLock#readLock}.
676 public static class ReadLock implements Lock, java.io.Serializable {
677 private static final long serialVersionUID = -5992448646407690164L;
678 private final Sync sync;
681 * Constructor for use by subclasses
683 * @param lock the outer lock object
684 * @throws NullPointerException if the lock is null
686 protected ReadLock(ReentrantReadWriteLock lock) {
691 * Acquires the read lock.
693 * <p>Acquires the read lock if the write lock is not held by
694 * another thread and returns immediately.
696 * <p>If the write lock is held by another thread then
697 * the current thread becomes disabled for thread scheduling
698 * purposes and lies dormant until the read lock has been acquired.
701 sync.acquireShared(1);
705 * Acquires the read lock unless the current thread is
706 * {@linkplain Thread#interrupt interrupted}.
708 * <p>Acquires the read lock if the write lock is not held
709 * by another thread and returns immediately.
711 * <p>If the write lock is held by another thread then the
712 * current thread becomes disabled for thread scheduling
713 * purposes and lies dormant until one of two things happens:
717 * <li>The read lock is acquired by the current thread; or
719 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
720 * the current thread.
724 * <p>If the current thread:
728 * <li>has its interrupted status set on entry to this method; or
730 * <li>is {@linkplain Thread#interrupt interrupted} while
731 * acquiring the read lock,
735 * then {@link InterruptedException} is thrown and the current
736 * thread's interrupted status is cleared.
738 * <p>In this implementation, as this method is an explicit
739 * interruption point, preference is given to responding to
740 * the interrupt over normal or reentrant acquisition of the
743 * @throws InterruptedException if the current thread is interrupted
745 public void lockInterruptibly() throws InterruptedException {
746 sync.acquireSharedInterruptibly(1);
750 * Acquires the read lock only if the write lock is not held by
751 * another thread at the time of invocation.
753 * <p>Acquires the read lock if the write lock is not held by
754 * another thread and returns immediately with the value
755 * {@code true}. Even when this lock has been set to use a
756 * fair ordering policy, a call to {@code tryLock()}
757 * <em>will</em> immediately acquire the read lock if it is
758 * available, whether or not other threads are currently
759 * waiting for the read lock. This "barging" behavior
760 * can be useful in certain circumstances, even though it
761 * breaks fairness. If you want to honor the fairness setting
762 * for this lock, then use {@link #tryLock(long, TimeUnit)
763 * tryLock(0, TimeUnit.SECONDS) } which is almost equivalent
764 * (it also detects interruption).
766 * <p>If the write lock is held by another thread then
767 * this method will return immediately with the value
770 * @return {@code true} if the read lock was acquired
772 public boolean tryLock() {
773 return sync.tryReadLock();
777 * Acquires the read lock if the write lock is not held by
778 * another thread within the given waiting time and the
779 * current thread has not been {@linkplain Thread#interrupt
782 * <p>Acquires the read lock if the write lock is not held by
783 * another thread and returns immediately with the value
784 * {@code true}. If this lock has been set to use a fair
785 * ordering policy then an available lock <em>will not</em> be
786 * acquired if any other threads are waiting for the
787 * lock. This is in contrast to the {@link #tryLock()}
788 * method. If you want a timed {@code tryLock} that does
789 * permit barging on a fair lock then combine the timed and
790 * un-timed forms together:
792 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
795 * <p>If the write lock is held by another thread then the
796 * current thread becomes disabled for thread scheduling
797 * purposes and lies dormant until one of three things happens:
801 * <li>The read lock is acquired by the current thread; or
803 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
804 * the current thread; or
806 * <li>The specified waiting time elapses.
810 * <p>If the read lock is acquired then the value {@code true} is
813 * <p>If the current thread:
817 * <li>has its interrupted status set on entry to this method; or
819 * <li>is {@linkplain Thread#interrupt interrupted} while
820 * acquiring the read lock,
822 * </ul> then {@link InterruptedException} is thrown and the
823 * current thread's interrupted status is cleared.
825 * <p>If the specified waiting time elapses then the value
826 * {@code false} is returned. If the time is less than or
827 * equal to zero, the method will not wait at all.
829 * <p>In this implementation, as this method is an explicit
830 * interruption point, preference is given to responding to
831 * the interrupt over normal or reentrant acquisition of the
832 * lock, and over reporting the elapse of the waiting time.
834 * @param timeout the time to wait for the read lock
835 * @param unit the time unit of the timeout argument
836 * @return {@code true} if the read lock was acquired
837 * @throws InterruptedException if the current thread is interrupted
838 * @throws NullPointerException if the time unit is null
841 public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
842 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
846 * Attempts to release this lock.
848 * <p> If the number of readers is now zero then the lock
849 * is made available for write lock attempts.
851 public void unlock() {
852 sync.releaseShared(1);
856 * Throws {@code UnsupportedOperationException} because
857 * {@code ReadLocks} do not support conditions.
859 * @throws UnsupportedOperationException always
861 public Condition newCondition() {
862 throw new UnsupportedOperationException();
866 * Returns a string identifying this lock, as well as its lock state.
867 * The state, in brackets, includes the String {@code "Read locks ="}
868 * followed by the number of held read locks.
870 * @return a string identifying this lock, as well as its lock state
872 public String toString() {
873 int r = sync.getReadLockCount();
874 return super.toString() +
875 "[Read locks = " + r + "]";
880 * The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
882 public static class WriteLock implements Lock, java.io.Serializable {
883 private static final long serialVersionUID = -4992448646407690164L;
884 private final Sync sync;
887 * Constructor for use by subclasses
889 * @param lock the outer lock object
890 * @throws NullPointerException if the lock is null
892 protected WriteLock(ReentrantReadWriteLock lock) {
897 * Acquires the write lock.
899 * <p>Acquires the write lock if neither the read nor write lock
900 * are held by another thread
901 * and returns immediately, setting the write lock hold count to
904 * <p>If the current thread already holds the write lock then the
905 * hold count is incremented by one and the method returns
908 * <p>If the lock is held by another thread then the current
909 * thread becomes disabled for thread scheduling purposes and
910 * lies dormant until the write lock has been acquired, at which
911 * time the write lock hold count is set to one.
918 * Acquires the write lock unless the current thread is
919 * {@linkplain Thread#interrupt interrupted}.
921 * <p>Acquires the write lock if neither the read nor write lock
922 * are held by another thread
923 * and returns immediately, setting the write lock hold count to
926 * <p>If the current thread already holds this lock then the
927 * hold count is incremented by one and the method returns
930 * <p>If the lock is held by another thread then the current
931 * thread becomes disabled for thread scheduling purposes and
932 * lies dormant until one of two things happens:
936 * <li>The write lock is acquired by the current thread; or
938 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
939 * the current thread.
943 * <p>If the write lock is acquired by the current thread then the
944 * lock hold count is set to one.
946 * <p>If the current thread:
950 * <li>has its interrupted status set on entry to this method;
953 * <li>is {@linkplain Thread#interrupt interrupted} while
954 * acquiring the write lock,
958 * then {@link InterruptedException} is thrown and the current
959 * thread's interrupted status is cleared.
961 * <p>In this implementation, as this method is an explicit
962 * interruption point, preference is given to responding to
963 * the interrupt over normal or reentrant acquisition of the
966 * @throws InterruptedException if the current thread is interrupted
968 public void lockInterruptibly() throws InterruptedException {
969 sync.acquireInterruptibly(1);
973 * Acquires the write lock only if it is not held by another thread
974 * at the time of invocation.
976 * <p>Acquires the write lock if neither the read nor write lock
977 * are held by another thread
978 * and returns immediately with the value {@code true},
979 * setting the write lock hold count to one. Even when this lock has
980 * been set to use a fair ordering policy, a call to
981 * {@code tryLock()} <em>will</em> immediately acquire the
982 * lock if it is available, whether or not other threads are
983 * currently waiting for the write lock. This "barging"
984 * behavior can be useful in certain circumstances, even
985 * though it breaks fairness. If you want to honor the
986 * fairness setting for this lock, then use {@link
987 * #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
988 * which is almost equivalent (it also detects interruption).
990 * <p> If the current thread already holds this lock then the
991 * hold count is incremented by one and the method returns
994 * <p>If the lock is held by another thread then this method
995 * will return immediately with the value {@code false}.
997 * @return {@code true} if the lock was free and was acquired
998 * by the current thread, or the write lock was already held
999 * by the current thread; and {@code false} otherwise.
1001 public boolean tryLock( ) {
1002 return sync.tryWriteLock();
1006 * Acquires the write lock if it is not held by another thread
1007 * within the given waiting time and the current thread has
1008 * not been {@linkplain Thread#interrupt interrupted}.
1010 * <p>Acquires the write lock if neither the read nor write lock
1011 * are held by another thread
1012 * and returns immediately with the value {@code true},
1013 * setting the write lock hold count to one. If this lock has been
1014 * set to use a fair ordering policy then an available lock
1015 * <em>will not</em> be acquired if any other threads are
1016 * waiting for the write lock. This is in contrast to the {@link
1017 * #tryLock()} method. If you want a timed {@code tryLock}
1018 * that does permit barging on a fair lock then combine the
1019 * timed and un-timed forms together:
1021 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
1024 * <p>If the current thread already holds this lock then the
1025 * hold count is incremented by one and the method returns
1028 * <p>If the lock is held by another thread then the current
1029 * thread becomes disabled for thread scheduling purposes and
1030 * lies dormant until one of three things happens:
1034 * <li>The write lock is acquired by the current thread; or
1036 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
1037 * the current thread; or
1039 * <li>The specified waiting time elapses
1043 * <p>If the write lock is acquired then the value {@code true} is
1044 * returned and the write lock hold count is set to one.
1046 * <p>If the current thread:
1050 * <li>has its interrupted status set on entry to this method;
1053 * <li>is {@linkplain Thread#interrupt interrupted} while
1054 * acquiring the write lock,
1058 * then {@link InterruptedException} is thrown and the current
1059 * thread's interrupted status is cleared.
1061 * <p>If the specified waiting time elapses then the value
1062 * {@code false} is returned. If the time is less than or
1063 * equal to zero, the method will not wait at all.
1065 * <p>In this implementation, as this method is an explicit
1066 * interruption point, preference is given to responding to
1067 * the interrupt over normal or reentrant acquisition of the
1068 * lock, and over reporting the elapse of the waiting time.
1070 * @param timeout the time to wait for the write lock
1071 * @param unit the time unit of the timeout argument
1073 * @return {@code true} if the lock was free and was acquired
1074 * by the current thread, or the write lock was already held by the
1075 * current thread; and {@code false} if the waiting time
1076 * elapsed before the lock could be acquired.
1078 * @throws InterruptedException if the current thread is interrupted
1079 * @throws NullPointerException if the time unit is null
1082 public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
1083 return sync.tryAcquireNanos(1, unit.toNanos(timeout));
1087 * Attempts to release this lock.
1089 * <p>If the current thread is the holder of this lock then
1090 * the hold count is decremented. If the hold count is now
1091 * zero then the lock is released. If the current thread is
1092 * not the holder of this lock then {@link
1093 * IllegalMonitorStateException} is thrown.
1095 * @throws IllegalMonitorStateException if the current thread does not
1098 public void unlock() {
1103 * Returns a {@link Condition} instance for use with this
1104 * {@link Lock} instance.
1105 * <p>The returned {@link Condition} instance supports the same
1106 * usages as do the {@link Object} monitor methods ({@link
1107 * Object#wait() wait}, {@link Object#notify notify}, and {@link
1108 * Object#notifyAll notifyAll}) when used with the built-in
1113 * <li>If this write lock is not held when any {@link
1114 * Condition} method is called then an {@link
1115 * IllegalMonitorStateException} is thrown. (Read locks are
1116 * held independently of write locks, so are not checked or
1117 * affected. However it is essentially always an error to
1118 * invoke a condition waiting method when the current thread
1119 * has also acquired read locks, since other threads that
1120 * could unblock it will not be able to acquire the write
1123 * <li>When the condition {@linkplain Condition#await() waiting}
1124 * methods are called the write lock is released and, before
1125 * they return, the write lock is reacquired and the lock hold
1126 * count restored to what it was when the method was called.
1128 * <li>If a thread is {@linkplain Thread#interrupt interrupted} while
1129 * waiting then the wait will terminate, an {@link
1130 * InterruptedException} will be thrown, and the thread's
1131 * interrupted status will be cleared.
1133 * <li> Waiting threads are signalled in FIFO order.
1135 * <li>The ordering of lock reacquisition for threads returning
1136 * from waiting methods is the same as for threads initially
1137 * acquiring the lock, which is in the default case not specified,
1138 * but for <em>fair</em> locks favors those threads that have been
1139 * waiting the longest.
1143 * @return the Condition object
1145 public Condition newCondition() {
1146 return sync.newCondition();
1150 * Returns a string identifying this lock, as well as its lock
1151 * state. The state, in brackets includes either the String
1152 * {@code "Unlocked"} or the String {@code "Locked by"}
1153 * followed by the {@linkplain Thread#getName name} of the owning thread.
1155 * @return a string identifying this lock, as well as its lock state
1157 public String toString() {
1158 Thread o = sync.getOwner();
1159 return super.toString() + ((o == null) ?
1161 "[Locked by thread " + o.getName() + "]");
1165 * Queries if this write lock is held by the current thread.
1166 * Identical in effect to {@link
1167 * ReentrantReadWriteLock#isWriteLockedByCurrentThread}.
1169 * @return {@code true} if the current thread holds this lock and
1170 * {@code false} otherwise
1173 public boolean isHeldByCurrentThread() {
1174 return sync.isHeldExclusively();
1178 * Queries the number of holds on this write lock by the current
1179 * thread. A thread has a hold on a lock for each lock action
1180 * that is not matched by an unlock action. Identical in effect
1181 * to {@link ReentrantReadWriteLock#getWriteHoldCount}.
1183 * @return the number of holds on this lock by the current thread,
1184 * or zero if this lock is not held by the current thread
1187 public int getHoldCount() {
1188 return sync.getWriteHoldCount();
1192 // Instrumentation and status
1195 * Returns {@code true} if this lock has fairness set true.
1197 * @return {@code true} if this lock has fairness set true
1199 public final boolean isFair() {
1200 return sync instanceof FairSync;
1204 * Returns the thread that currently owns the write lock, or
1205 * {@code null} if not owned. When this method is called by a
1206 * thread that is not the owner, the return value reflects a
1207 * best-effort approximation of current lock status. For example,
1208 * the owner may be momentarily {@code null} even if there are
1209 * threads trying to acquire the lock but have not yet done so.
1210 * This method is designed to facilitate construction of
1211 * subclasses that provide more extensive lock monitoring
1214 * @return the owner, or {@code null} if not owned
1216 protected Thread getOwner() {
1217 return sync.getOwner();
1221 * Queries the number of read locks held for this lock. This
1222 * method is designed for use in monitoring system state, not for
1223 * synchronization control.
1224 * @return the number of read locks held.
1226 public int getReadLockCount() {
1227 return sync.getReadLockCount();
1231 * Queries if the write lock is held by any thread. This method is
1232 * designed for use in monitoring system state, not for
1233 * synchronization control.
1235 * @return {@code true} if any thread holds the write lock and
1236 * {@code false} otherwise
1238 public boolean isWriteLocked() {
1239 return sync.isWriteLocked();
1243 * Queries if the write lock is held by the current thread.
1245 * @return {@code true} if the current thread holds the write lock and
1246 * {@code false} otherwise
1248 public boolean isWriteLockedByCurrentThread() {
1249 return sync.isHeldExclusively();
1253 * Queries the number of reentrant write holds on this lock by the
1254 * current thread. A writer thread has a hold on a lock for
1255 * each lock action that is not matched by an unlock action.
1257 * @return the number of holds on the write lock by the current thread,
1258 * or zero if the write lock is not held by the current thread
1260 public int getWriteHoldCount() {
1261 return sync.getWriteHoldCount();
1265 * Queries the number of reentrant read holds on this lock by the
1266 * current thread. A reader thread has a hold on a lock for
1267 * each lock action that is not matched by an unlock action.
1269 * @return the number of holds on the read lock by the current thread,
1270 * or zero if the read lock is not held by the current thread
1273 public int getReadHoldCount() {
1274 return sync.getReadHoldCount();
1278 * Returns a collection containing threads that may be waiting to
1279 * acquire the write lock. Because the actual set of threads may
1280 * change dynamically while constructing this result, the returned
1281 * collection is only a best-effort estimate. The elements of the
1282 * returned collection are in no particular order. This method is
1283 * designed to facilitate construction of subclasses that provide
1284 * more extensive lock monitoring facilities.
1286 * @return the collection of threads
1288 protected Collection<Thread> getQueuedWriterThreads() {
1289 return sync.getExclusiveQueuedThreads();
1293 * Returns a collection containing threads that may be waiting to
1294 * acquire the read lock. Because the actual set of threads may
1295 * change dynamically while constructing this result, the returned
1296 * collection is only a best-effort estimate. The elements of the
1297 * returned collection are in no particular order. This method is
1298 * designed to facilitate construction of subclasses that provide
1299 * more extensive lock monitoring facilities.
1301 * @return the collection of threads
1303 protected Collection<Thread> getQueuedReaderThreads() {
1304 return sync.getSharedQueuedThreads();
1308 * Queries whether any threads are waiting to acquire the read or
1309 * write lock. Note that because cancellations may occur at any
1310 * time, a {@code true} return does not guarantee that any other
1311 * thread will ever acquire a lock. This method is designed
1312 * primarily for use in monitoring of the system state.
1314 * @return {@code true} if there may be other threads waiting to
1317 public final boolean hasQueuedThreads() {
1318 return sync.hasQueuedThreads();
1322 * Queries whether the given thread is waiting to acquire either
1323 * the read or write lock. Note that because cancellations may
1324 * occur at any time, a {@code true} return does not guarantee
1325 * that this thread will ever acquire a lock. This method is
1326 * designed primarily for use in monitoring of the system state.
1328 * @param thread the thread
1329 * @return {@code true} if the given thread is queued waiting for this lock
1330 * @throws NullPointerException if the thread is null
1332 public final boolean hasQueuedThread(Thread thread) {
1333 return sync.isQueued(thread);
1337 * Returns an estimate of the number of threads waiting to acquire
1338 * either the read or write lock. The value is only an estimate
1339 * because the number of threads may change dynamically while this
1340 * method traverses internal data structures. This method is
1341 * designed for use in monitoring of the system state, not for
1342 * synchronization control.
1344 * @return the estimated number of threads waiting for this lock
1346 public final int getQueueLength() {
1347 return sync.getQueueLength();
1351 * Returns a collection containing threads that may be waiting to
1352 * acquire either the read or write lock. Because the actual set
1353 * of threads may change dynamically while constructing this
1354 * result, the returned collection is only a best-effort estimate.
1355 * The elements of the returned collection are in no particular
1356 * order. This method is designed to facilitate construction of
1357 * subclasses that provide more extensive monitoring facilities.
1359 * @return the collection of threads
1361 protected Collection<Thread> getQueuedThreads() {
1362 return sync.getQueuedThreads();
1366 * Queries whether any threads are waiting on the given condition
1367 * associated with the write lock. Note that because timeouts and
1368 * interrupts may occur at any time, a {@code true} return does
1369 * not guarantee that a future {@code signal} will awaken any
1370 * threads. This method is designed primarily for use in
1371 * monitoring of the system state.
1373 * @param condition the condition
1374 * @return {@code true} if there are any waiting threads
1375 * @throws IllegalMonitorStateException if this lock is not held
1376 * @throws IllegalArgumentException if the given condition is
1377 * not associated with this lock
1378 * @throws NullPointerException if the condition is null
1380 public boolean hasWaiters(Condition condition) {
1381 if (condition == null)
1382 throw new NullPointerException();
1383 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1384 throw new IllegalArgumentException("not owner");
1385 return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
1389 * Returns an estimate of the number of threads waiting on the
1390 * given condition associated with the write lock. Note that because
1391 * timeouts and interrupts may occur at any time, the estimate
1392 * serves only as an upper bound on the actual number of waiters.
1393 * This method is designed for use in monitoring of the system
1394 * state, not for synchronization control.
1396 * @param condition the condition
1397 * @return the estimated number of waiting threads
1398 * @throws IllegalMonitorStateException if this lock is not held
1399 * @throws IllegalArgumentException if the given condition is
1400 * not associated with this lock
1401 * @throws NullPointerException if the condition is null
1403 public int getWaitQueueLength(Condition condition) {
1404 if (condition == null)
1405 throw new NullPointerException();
1406 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1407 throw new IllegalArgumentException("not owner");
1408 return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
1412 * Returns a collection containing those threads that may be
1413 * waiting on the given condition associated with the write lock.
1414 * Because the actual set of threads may change dynamically while
1415 * constructing this result, the returned collection is only a
1416 * best-effort estimate. The elements of the returned collection
1417 * are in no particular order. This method is designed to
1418 * facilitate construction of subclasses that provide more
1419 * extensive condition monitoring facilities.
1421 * @param condition the condition
1422 * @return the collection of threads
1423 * @throws IllegalMonitorStateException if this lock is not held
1424 * @throws IllegalArgumentException if the given condition is
1425 * not associated with this lock
1426 * @throws NullPointerException if the condition is null
1428 protected Collection<Thread> getWaitingThreads(Condition condition) {
1429 if (condition == null)
1430 throw new NullPointerException();
1431 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
1432 throw new IllegalArgumentException("not owner");
1433 return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
1437 * Returns a string identifying this lock, as well as its lock state.
1438 * The state, in brackets, includes the String {@code "Write locks ="}
1439 * followed by the number of reentrantly held write locks, and the
1440 * String {@code "Read locks ="} followed by the number of held
1443 * @return a string identifying this lock, as well as its lock state
1445 public String toString() {
1446 int c = sync.getCount();
1447 int w = Sync.exclusiveCount(c);
1448 int r = Sync.sharedCount(c);
1450 return super.toString() +
1451 "[Write locks = " + w + ", Read locks = " + r + "]";