ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/jdk7/java/util/concurrent/locks/ReentrantReadWriteLock.java
Revision: 1.11
Committed: Sat Oct 17 01:46:23 2015 UTC (8 years, 7 months ago) by jsr166
Branch: MAIN
CVS Tags: HEAD
Changes since 1.10: +2 -2 lines
Log Message:
prefer List to primitive array

File Contents

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