ReentrantReadWriteLock.java revision cec4dd4b1d33f78997603d0f89c0d0e56e64dbcd
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/licenses/publicdomain
5 */
6
7package java.util.concurrent.locks;
8import java.util.concurrent.*;
9import java.util.concurrent.atomic.*;
10import java.util.*;
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 acquire the lock if it is
55 * 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 String[] allKeys() {
163 *        r.lock();
164 *        try { return m.keySet().toArray(); }
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 */
189public 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 */
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    static abstract 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 = null;
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         * Reconstitute this lock instance from a stream
628         * @param s the stream
629         */
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
635        }
636
637        final int getCount() { return getState(); }
638    }
639
640    /**
641     * Nonfair version of Sync
642     */
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
647        }
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.
655             */
656            return apparentlyFirstQueuedIsExclusive();
657        }
658    }
659
660    /**
661     * Fair version of Sync
662     */
663    final static class FairSync extends Sync {
664        private static final long serialVersionUID = -2274990926593161451L;
665        final boolean writerShouldBlock() {
666            return hasQueuedPredecessors();
667        }
668        final boolean readerShouldBlock() {
669            return hasQueuedPredecessors();
670        }
671    }
672
673    /**
674     * The lock returned by method {@link ReentrantReadWriteLock#readLock}.
675     */
676    public static class ReadLock implements Lock, java.io.Serializable  {
677        private static final long serialVersionUID = -5992448646407690164L;
678        private final Sync sync;
679
680        /**
681         * Constructor for use by subclasses
682         *
683         * @param lock the outer lock object
684         * @throws NullPointerException if the lock is null
685         */
686        protected ReadLock(ReentrantReadWriteLock lock) {
687            sync = lock.sync;
688        }
689
690        /**
691         * Acquires the read lock.
692         *
693         * <p>Acquires the read lock if the write lock is not held by
694         * another thread and returns immediately.
695         *
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.
699         */
700        public void lock() {
701            sync.acquireShared(1);
702        }
703
704        /**
705         * Acquires the read lock unless the current thread is
706         * {@linkplain Thread#interrupt interrupted}.
707         *
708         * <p>Acquires the read lock if the write lock is not held
709         * by another thread and returns immediately.
710         *
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:
714         *
715         * <ul>
716         *
717         * <li>The read lock is acquired by the current thread; or
718         *
719         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
720         * the current thread.
721         *
722         * </ul>
723         *
724         * <p>If the current thread:
725         *
726         * <ul>
727         *
728         * <li>has its interrupted status set on entry to this method; or
729         *
730         * <li>is {@linkplain Thread#interrupt interrupted} while
731         * acquiring the read lock,
732         *
733         * </ul>
734         *
735         * then {@link InterruptedException} is thrown and the current
736         * thread's interrupted status is cleared.
737         *
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
741         * lock.
742         *
743         * @throws InterruptedException if the current thread is interrupted
744         */
745        public void lockInterruptibly() throws InterruptedException {
746            sync.acquireSharedInterruptibly(1);
747        }
748
749        /**
750         * Acquires the read lock only if the write lock is not held by
751         * another thread at the time of invocation.
752         *
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 &quot;barging&quot; 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).
765         *
766         * <p>If the write lock is held by another thread then
767         * this method will return immediately with the value
768         * {@code false}.
769         *
770         * @return {@code true} if the read lock was acquired
771         */
772        public  boolean tryLock() {
773            return sync.tryReadLock();
774        }
775
776        /**
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
780         * interrupted}.
781         *
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:
791         *
792         * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
793         * </pre>
794         *
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:
798         *
799         * <ul>
800         *
801         * <li>The read lock is acquired by the current thread; or
802         *
803         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
804         * the current thread; or
805         *
806         * <li>The specified waiting time elapses.
807         *
808         * </ul>
809         *
810         * <p>If the read lock is acquired then the value {@code true} is
811         * returned.
812         *
813         * <p>If the current thread:
814         *
815         * <ul>
816         *
817         * <li>has its interrupted status set on entry to this method; or
818         *
819         * <li>is {@linkplain Thread#interrupt interrupted} while
820         * acquiring the read lock,
821         *
822         * </ul> then {@link InterruptedException} is thrown and the
823         * current thread's interrupted status is cleared.
824         *
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.
828         *
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.
833         *
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
839         *
840         */
841        public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
842            return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
843        }
844
845        /**
846         * Attempts to release this lock.
847         *
848         * <p> If the number of readers is now zero then the lock
849         * is made available for write lock attempts.
850         */
851        public  void unlock() {
852            sync.releaseShared(1);
853        }
854
855        /**
856         * Throws {@code UnsupportedOperationException} because
857         * {@code ReadLocks} do not support conditions.
858         *
859         * @throws UnsupportedOperationException always
860         */
861        public Condition newCondition() {
862            throw new UnsupportedOperationException();
863        }
864
865        /**
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.
869         *
870         * @return a string identifying this lock, as well as its lock state
871         */
872        public String toString() {
873            int r = sync.getReadLockCount();
874            return super.toString() +
875                "[Read locks = " + r + "]";
876        }
877    }
878
879    /**
880     * The lock returned by method {@link ReentrantReadWriteLock#writeLock}.
881     */
882    public static class WriteLock implements Lock, java.io.Serializable  {
883        private static final long serialVersionUID = -4992448646407690164L;
884        private final Sync sync;
885
886        /**
887         * Constructor for use by subclasses
888         *
889         * @param lock the outer lock object
890         * @throws NullPointerException if the lock is null
891         */
892        protected WriteLock(ReentrantReadWriteLock lock) {
893            sync = lock.sync;
894        }
895
896        /**
897         * Acquires the write lock.
898         *
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
902         * one.
903         *
904         * <p>If the current thread already holds the write lock then the
905         * hold count is incremented by one and the method returns
906         * immediately.
907         *
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.
912         */
913        public void lock() {
914            sync.acquire(1);
915        }
916
917        /**
918         * Acquires the write lock unless the current thread is
919         * {@linkplain Thread#interrupt interrupted}.
920         *
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
924         * one.
925         *
926         * <p>If the current thread already holds this lock then the
927         * hold count is incremented by one and the method returns
928         * immediately.
929         *
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:
933         *
934         * <ul>
935         *
936         * <li>The write lock is acquired by the current thread; or
937         *
938         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
939         * the current thread.
940         *
941         * </ul>
942         *
943         * <p>If the write lock is acquired by the current thread then the
944         * lock hold count is set to one.
945         *
946         * <p>If the current thread:
947         *
948         * <ul>
949         *
950         * <li>has its interrupted status set on entry to this method;
951         * or
952         *
953         * <li>is {@linkplain Thread#interrupt interrupted} while
954         * acquiring the write lock,
955         *
956         * </ul>
957         *
958         * then {@link InterruptedException} is thrown and the current
959         * thread's interrupted status is cleared.
960         *
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
964         * lock.
965         *
966         * @throws InterruptedException if the current thread is interrupted
967         */
968        public void lockInterruptibly() throws InterruptedException {
969            sync.acquireInterruptibly(1);
970        }
971
972        /**
973         * Acquires the write lock only if it is not held by another thread
974         * at the time of invocation.
975         *
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 &quot;barging&quot;
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).
989         *
990         * <p> If the current thread already holds this lock then the
991         * hold count is incremented by one and the method returns
992         * {@code true}.
993         *
994         * <p>If the lock is held by another thread then this method
995         * will return immediately with the value {@code false}.
996         *
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.
1000         */
1001        public boolean tryLock( ) {
1002            return sync.tryWriteLock();
1003        }
1004
1005        /**
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}.
1009         *
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:
1020         *
1021         * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
1022         * </pre>
1023         *
1024         * <p>If the current thread already holds this lock then the
1025         * hold count is incremented by one and the method returns
1026         * {@code true}.
1027         *
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:
1031         *
1032         * <ul>
1033         *
1034         * <li>The write lock is acquired by the current thread; or
1035         *
1036         * <li>Some other thread {@linkplain Thread#interrupt interrupts}
1037         * the current thread; or
1038         *
1039         * <li>The specified waiting time elapses
1040         *
1041         * </ul>
1042         *
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.
1045         *
1046         * <p>If the current thread:
1047         *
1048         * <ul>
1049         *
1050         * <li>has its interrupted status set on entry to this method;
1051         * or
1052         *
1053         * <li>is {@linkplain Thread#interrupt interrupted} while
1054         * acquiring the write lock,
1055         *
1056         * </ul>
1057         *
1058         * then {@link InterruptedException} is thrown and the current
1059         * thread's interrupted status is cleared.
1060         *
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.
1064         *
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.
1069         *
1070         * @param timeout the time to wait for the write lock
1071         * @param unit the time unit of the timeout argument
1072         *
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.
1077         *
1078         * @throws InterruptedException if the current thread is interrupted
1079         * @throws NullPointerException if the time unit is null
1080         *
1081         */
1082        public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
1083            return sync.tryAcquireNanos(1, unit.toNanos(timeout));
1084        }
1085
1086        /**
1087         * Attempts to release this lock.
1088         *
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.
1094         *
1095         * @throws IllegalMonitorStateException if the current thread does not
1096         * hold this lock.
1097         */
1098        public void unlock() {
1099            sync.release(1);
1100        }
1101
1102        /**
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
1109         * monitor lock.
1110         *
1111         * <ul>
1112         *
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
1121         * lock.)
1122         *
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.
1127         *
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.
1132         *
1133         * <li> Waiting threads are signalled in FIFO order.
1134         *
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.
1140         *
1141         * </ul>
1142         *
1143         * @return the Condition object
1144         */
1145        public Condition newCondition() {
1146            return sync.newCondition();
1147        }
1148
1149        /**
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.
1154         *
1155         * @return a string identifying this lock, as well as its lock state
1156         */
1157        public String toString() {
1158            Thread o = sync.getOwner();
1159            return super.toString() + ((o == null) ?
1160                                       "[Unlocked]" :
1161                                       "[Locked by thread " + o.getName() + "]");
1162        }
1163
1164        /**
1165         * Queries if this write lock is held by the current thread.
1166         * Identical in effect to {@link
1167         * ReentrantReadWriteLock#isWriteLockedByCurrentThread}.
1168         *
1169         * @return {@code true} if the current thread holds this lock and
1170         *         {@code false} otherwise
1171         * @since 1.6
1172         */
1173        public boolean isHeldByCurrentThread() {
1174            return sync.isHeldExclusively();
1175        }
1176
1177        /**
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}.
1182         *
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
1185         * @since 1.6
1186         */
1187        public int getHoldCount() {
1188            return sync.getWriteHoldCount();
1189        }
1190    }
1191
1192    // Instrumentation and status
1193
1194    /**
1195     * Returns {@code true} if this lock has fairness set true.
1196     *
1197     * @return {@code true} if this lock has fairness set true
1198     */
1199    public final boolean isFair() {
1200        return sync instanceof FairSync;
1201    }
1202
1203    /**
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
1212     * facilities.
1213     *
1214     * @return the owner, or {@code null} if not owned
1215     */
1216    protected Thread getOwner() {
1217        return sync.getOwner();
1218    }
1219
1220    /**
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.
1225     */
1226    public int getReadLockCount() {
1227        return sync.getReadLockCount();
1228    }
1229
1230    /**
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.
1234     *
1235     * @return {@code true} if any thread holds the write lock and
1236     *         {@code false} otherwise
1237     */
1238    public boolean isWriteLocked() {
1239        return sync.isWriteLocked();
1240    }
1241
1242    /**
1243     * Queries if the write lock is held by the current thread.
1244     *
1245     * @return {@code true} if the current thread holds the write lock and
1246     *         {@code false} otherwise
1247     */
1248    public boolean isWriteLockedByCurrentThread() {
1249        return sync.isHeldExclusively();
1250    }
1251
1252    /**
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.
1256     *
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
1259     */
1260    public int getWriteHoldCount() {
1261        return sync.getWriteHoldCount();
1262    }
1263
1264    /**
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.
1268     *
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
1271     * @since 1.6
1272     */
1273    public int getReadHoldCount() {
1274        return sync.getReadHoldCount();
1275    }
1276
1277    /**
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.
1285     *
1286     * @return the collection of threads
1287     */
1288    protected Collection<Thread> getQueuedWriterThreads() {
1289        return sync.getExclusiveQueuedThreads();
1290    }
1291
1292    /**
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.
1300     *
1301     * @return the collection of threads
1302     */
1303    protected Collection<Thread> getQueuedReaderThreads() {
1304        return sync.getSharedQueuedThreads();
1305    }
1306
1307    /**
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.
1313     *
1314     * @return {@code true} if there may be other threads waiting to
1315     *         acquire the lock
1316     */
1317    public final boolean hasQueuedThreads() {
1318        return sync.hasQueuedThreads();
1319    }
1320
1321    /**
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.
1327     *
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
1331     */
1332    public final boolean hasQueuedThread(Thread thread) {
1333        return sync.isQueued(thread);
1334    }
1335
1336    /**
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.
1343     *
1344     * @return the estimated number of threads waiting for this lock
1345     */
1346    public final int getQueueLength() {
1347        return sync.getQueueLength();
1348    }
1349
1350    /**
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.
1358     *
1359     * @return the collection of threads
1360     */
1361    protected Collection<Thread> getQueuedThreads() {
1362        return sync.getQueuedThreads();
1363    }
1364
1365    /**
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.
1372     *
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
1379     */
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);
1386    }
1387
1388    /**
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.
1395     *
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
1402     */
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);
1409    }
1410
1411    /**
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.
1420     *
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
1427     */
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);
1434    }
1435
1436    /**
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
1441     * read locks.
1442     *
1443     * @return a string identifying this lock, as well as its lock state
1444     */
1445    public String toString() {
1446        int c = sync.getCount();
1447        int w = Sync.exclusiveCount(c);
1448        int r = Sync.sharedCount(c);
1449
1450        return super.toString() +
1451            "[Write locks = " + w + ", Read locks = " + r + "]";
1452    }
1453
1454}
1455