View Javadoc
1   /*
2    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
3    *
4    * This code is free software; you can redistribute it and/or modify it
5    * under the terms of the GNU General Public License version 2 only, as
6    * published by the Free Software Foundation.  Oracle designates this
7    * particular file as subject to the "Classpath" exception as provided
8    * by Oracle in the LICENSE file that accompanied this code.
9    *
10   * This code is distributed in the hope that it will be useful, but WITHOUT
11   * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
12   * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
13   * version 2 for more details (a copy is included in the LICENSE file that
14   * accompanied this code).
15   *
16   * You should have received a copy of the GNU General Public License version
17   * 2 along with this work; if not, write to the Free Software Foundation,
18   * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
19   *
20   * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
21   * or visit www.oracle.com if you need additional information or have any
22   * questions.
23   */
24  
25  /*
26   * This file is available under and governed by the GNU General Public
27   * License version 2 only, as published by the Free Software Foundation.
28   * However, the following notice accompanied the original version of this
29   * file:
30   *
31   * Written by Doug Lea with assistance from members of JCP JSR-166
32   * Expert Group and released to the public domain, as explained at
33   * http://creativecommons.org/publicdomain/zero/1.0/
34   */
35  
36  package java.util.concurrent.locks;
37  import java.util.concurrent.TimeUnit;
38  import java.util.Collection;
39  
40  /**
41   * A reentrant mutual exclusion {@link Lock} with the same basic
42   * behavior and semantics as the implicit monitor lock accessed using
43   * {@code synchronized} methods and statements, but with extended
44   * capabilities.
45   *
46   * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last
47   * successfully locking, but not yet unlocking it. A thread invoking
48   * {@code lock} will return, successfully acquiring the lock, when
49   * the lock is not owned by another thread. The method will return
50   * immediately if the current thread already owns the lock. This can
51   * be checked using methods {@link #isHeldByCurrentThread}, and {@link
52   * #getHoldCount}.
53   *
54   * <p>The constructor for this class accepts an optional
55   * <em>fairness</em> parameter.  When set {@code true}, under
56   * contention, locks favor granting access to the longest-waiting
57   * thread.  Otherwise this lock does not guarantee any particular
58   * access order.  Programs using fair locks accessed by many threads
59   * may display lower overall throughput (i.e., are slower; often much
60   * slower) than those using the default setting, but have smaller
61   * variances in times to obtain locks and guarantee lack of
62   * starvation. Note however, that fairness of locks does not guarantee
63   * fairness of thread scheduling. Thus, one of many threads using a
64   * fair lock may obtain it multiple times in succession while other
65   * active threads are not progressing and not currently holding the
66   * lock.
67   * Also note that the untimed {@link #tryLock()} method does not
68   * honor the fairness setting. It will succeed if the lock
69   * is available even if other threads are waiting.
70   *
71   * <p>It is recommended practice to <em>always</em> immediately
72   * follow a call to {@code lock} with a {@code try} block, most
73   * typically in a before/after construction such as:
74   *
75   *  <pre> {@code
76   * class X {
77   *   private final ReentrantLock lock = new ReentrantLock();
78   *   // ...
79   *
80   *   public void m() {
81   *     lock.lock();  // block until condition holds
82   *     try {
83   *       // ... method body
84   *     } finally {
85   *       lock.unlock()
86   *     }
87   *   }
88   * }}</pre>
89   *
90   * <p>In addition to implementing the {@link Lock} interface, this
91   * class defines a number of {@code public} and {@code protected}
92   * methods for inspecting the state of the lock.  Some of these
93   * methods are only useful for instrumentation and monitoring.
94   *
95   * <p>Serialization of this class behaves in the same way as built-in
96   * locks: a deserialized lock is in the unlocked state, regardless of
97   * its state when serialized.
98   *
99   * <p>This lock supports a maximum of 2147483647 recursive locks by
100  * the same thread. Attempts to exceed this limit result in
101  * {@link Error} throws from locking methods.
102  *
103  * @since 1.5
104  * @author Doug Lea
105  */
106 public class ReentrantLock implements Lock, java.io.Serializable {
107     private static final long serialVersionUID = 7373984872572414699L;
108     /** Synchronizer providing all implementation mechanics */
109     private final Sync sync;
110 
111     /**
112      * Base of synchronization control for this lock. Subclassed
113      * into fair and nonfair versions below. Uses AQS state to
114      * represent the number of holds on the lock.
115      */
116     abstract static class Sync extends AbstractQueuedSynchronizer {
117         private static final long serialVersionUID = -5179523762034025860L;
118 
119         /**
120          * Performs {@link Lock#lock}. The main reason for subclassing
121          * is to allow fast path for nonfair version.
122          */
123         abstract void lock();
124 
125         /**
126          * Performs non-fair tryLock.  tryAcquire is implemented in
127          * subclasses, but both need nonfair try for trylock method.
128          */
129         final boolean nonfairTryAcquire(int acquires) {
130             final Thread current = Thread.currentThread();
131             int c = getState();
132             if (c == 0) {
133                 if (compareAndSetState(0, acquires)) {
134                     setExclusiveOwnerThread(current);
135                     return true;
136                 }
137             }
138             else if (current == getExclusiveOwnerThread()) {
139                 int nextc = c + acquires;
140                 if (nextc < 0) // overflow
141                     throw new Error("Maximum lock count exceeded");
142                 setState(nextc);
143                 return true;
144             }
145             return false;
146         }
147 
148         protected final boolean tryRelease(int releases) {
149             int c = getState() - releases;
150             if (Thread.currentThread() != getExclusiveOwnerThread())
151                 throw new IllegalMonitorStateException();
152             boolean free = false;
153             if (c == 0) {
154                 free = true;
155                 setExclusiveOwnerThread(null);
156             }
157             setState(c);
158             return free;
159         }
160 
161         protected final boolean isHeldExclusively() {
162             // While we must in general read state before owner,
163             // we don't need to do so to check if current thread is owner
164             return getExclusiveOwnerThread() == Thread.currentThread();
165         }
166 
167         final ConditionObject newCondition() {
168             return new ConditionObject();
169         }
170 
171         // Methods relayed from outer class
172 
173         final Thread getOwner() {
174             return getState() == 0 ? null : getExclusiveOwnerThread();
175         }
176 
177         final int getHoldCount() {
178             return isHeldExclusively() ? getState() : 0;
179         }
180 
181         final boolean isLocked() {
182             return getState() != 0;
183         }
184 
185         /**
186          * Reconstitutes the instance from a stream (that is, deserializes it).
187          */
188         private void readObject(java.io.ObjectInputStream s)
189             throws java.io.IOException, ClassNotFoundException {
190             s.defaultReadObject();
191             setState(0); // reset to unlocked state
192         }
193     }
194 
195     /**
196      * Sync object for non-fair locks
197      */
198     static final class NonfairSync extends Sync {
199         private static final long serialVersionUID = 7316153563782823691L;
200 
201         /**
202          * Performs lock.  Try immediate barge, backing up to normal
203          * acquire on failure.
204          */
205         final void lock() {
206             if (compareAndSetState(0, 1))
207                 setExclusiveOwnerThread(Thread.currentThread());
208             else
209                 acquire(1);
210         }
211 
212         protected final boolean tryAcquire(int acquires) {
213             return nonfairTryAcquire(acquires);
214         }
215     }
216 
217     /**
218      * Sync object for fair locks
219      */
220     static final class FairSync extends Sync {
221         private static final long serialVersionUID = -3000897897090466540L;
222 
223         final void lock() {
224             acquire(1);
225         }
226 
227         /**
228          * Fair version of tryAcquire.  Don't grant access unless
229          * recursive call or no waiters or is first.
230          */
231         protected final boolean tryAcquire(int acquires) {
232             final Thread current = Thread.currentThread();
233             int c = getState();
234             if (c == 0) {
235                 if (!hasQueuedPredecessors() &&
236                     compareAndSetState(0, acquires)) {
237                     setExclusiveOwnerThread(current);
238                     return true;
239                 }
240             }
241             else if (current == getExclusiveOwnerThread()) {
242                 int nextc = c + acquires;
243                 if (nextc < 0)
244                     throw new Error("Maximum lock count exceeded");
245                 setState(nextc);
246                 return true;
247             }
248             return false;
249         }
250     }
251 
252     /**
253      * Creates an instance of {@code ReentrantLock}.
254      * This is equivalent to using {@code ReentrantLock(false)}.
255      */
256     public ReentrantLock() {
257         sync = new NonfairSync();
258     }
259 
260     /**
261      * Creates an instance of {@code ReentrantLock} with the
262      * given fairness policy.
263      *
264      * @param fair {@code true} if this lock should use a fair ordering policy
265      */
266     public ReentrantLock(boolean fair) {
267         sync = fair ? new FairSync() : new NonfairSync();
268     }
269 
270     /**
271      * Acquires the lock.
272      *
273      * <p>Acquires the lock if it is not held by another thread and returns
274      * immediately, setting the lock hold count to one.
275      *
276      * <p>If the current thread already holds the lock then the hold
277      * count is incremented by one and the method returns immediately.
278      *
279      * <p>If the lock is held by another thread then the
280      * current thread becomes disabled for thread scheduling
281      * purposes and lies dormant until the lock has been acquired,
282      * at which time the lock hold count is set to one.
283      */
284     public void lock() {
285         sync.lock();
286     }
287 
288     /**
289      * Acquires the lock unless the current thread is
290      * {@linkplain Thread#interrupt interrupted}.
291      *
292      * <p>Acquires the lock if it is not held by another thread and returns
293      * immediately, setting the lock hold count to one.
294      *
295      * <p>If the current thread already holds this lock then the hold count
296      * is incremented by one and the method returns immediately.
297      *
298      * <p>If the lock is held by another thread then the
299      * current thread becomes disabled for thread scheduling
300      * purposes and lies dormant until one of two things happens:
301      *
302      * <ul>
303      *
304      * <li>The lock is acquired by the current thread; or
305      *
306      * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
307      * current thread.
308      *
309      * </ul>
310      *
311      * <p>If the lock is acquired by the current thread then the lock hold
312      * count is set to one.
313      *
314      * <p>If the current thread:
315      *
316      * <ul>
317      *
318      * <li>has its interrupted status set on entry to this method; or
319      *
320      * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
321      * the lock,
322      *
323      * </ul>
324      *
325      * then {@link InterruptedException} is thrown and the current thread's
326      * interrupted status is cleared.
327      *
328      * <p>In this implementation, as this method is an explicit
329      * interruption point, preference is given to responding to the
330      * interrupt over normal or reentrant acquisition of the lock.
331      *
332      * @throws InterruptedException if the current thread is interrupted
333      */
334     public void lockInterruptibly() throws InterruptedException {
335         sync.acquireInterruptibly(1);
336     }
337 
338     /**
339      * Acquires the lock only if it is not held by another thread at the time
340      * of invocation.
341      *
342      * <p>Acquires the lock if it is not held by another thread and
343      * returns immediately with the value {@code true}, setting the
344      * lock hold count to one. Even when this lock has been set to use a
345      * fair ordering policy, a call to {@code tryLock()} <em>will</em>
346      * immediately acquire the lock if it is available, whether or not
347      * other threads are currently waiting for the lock.
348      * This &quot;barging&quot; behavior can be useful in certain
349      * circumstances, even though it breaks fairness. If you want to honor
350      * the fairness setting for this lock, then use
351      * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
352      * which is almost equivalent (it also detects interruption).
353      *
354      * <p>If the current thread already holds this lock then the hold
355      * count is incremented by one and the method returns {@code true}.
356      *
357      * <p>If the lock is held by another thread then this method will return
358      * immediately with the value {@code false}.
359      *
360      * @return {@code true} if the lock was free and was acquired by the
361      *         current thread, or the lock was already held by the current
362      *         thread; and {@code false} otherwise
363      */
364     public boolean tryLock() {
365         return sync.nonfairTryAcquire(1);
366     }
367 
368     /**
369      * Acquires the lock if it is not held by another thread within the given
370      * waiting time and the current thread has not been
371      * {@linkplain Thread#interrupt interrupted}.
372      *
373      * <p>Acquires the lock if it is not held by another thread and returns
374      * immediately with the value {@code true}, setting the lock hold count
375      * to one. If this lock has been set to use a fair ordering policy then
376      * an available lock <em>will not</em> be acquired if any other threads
377      * are waiting for the lock. This is in contrast to the {@link #tryLock()}
378      * method. If you want a timed {@code tryLock} that does permit barging on
379      * a fair lock then combine the timed and un-timed forms together:
380      *
381      *  <pre> {@code
382      * if (lock.tryLock() ||
383      *     lock.tryLock(timeout, unit)) {
384      *   ...
385      * }}</pre>
386      *
387      * <p>If the current thread
388      * already holds this lock then the hold count is incremented by one and
389      * the method returns {@code true}.
390      *
391      * <p>If the lock is held by another thread then the
392      * current thread becomes disabled for thread scheduling
393      * purposes and lies dormant until one of three things happens:
394      *
395      * <ul>
396      *
397      * <li>The lock is acquired by the current thread; or
398      *
399      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
400      * the current thread; or
401      *
402      * <li>The specified waiting time elapses
403      *
404      * </ul>
405      *
406      * <p>If the lock is acquired then the value {@code true} is returned and
407      * the lock hold count is set to one.
408      *
409      * <p>If the current thread:
410      *
411      * <ul>
412      *
413      * <li>has its interrupted status set on entry to this method; or
414      *
415      * <li>is {@linkplain Thread#interrupt interrupted} while
416      * acquiring the lock,
417      *
418      * </ul>
419      * then {@link InterruptedException} is thrown and the current thread's
420      * interrupted status is cleared.
421      *
422      * <p>If the specified waiting time elapses then the value {@code false}
423      * is returned.  If the time is less than or equal to zero, the method
424      * will not wait at all.
425      *
426      * <p>In this implementation, as this method is an explicit
427      * interruption point, preference is given to responding to the
428      * interrupt over normal or reentrant acquisition of the lock, and
429      * over reporting the elapse of the waiting time.
430      *
431      * @param timeout the time to wait for the lock
432      * @param unit the time unit of the timeout argument
433      * @return {@code true} if the lock was free and was acquired by the
434      *         current thread, or the lock was already held by the current
435      *         thread; and {@code false} if the waiting time elapsed before
436      *         the lock could be acquired
437      * @throws InterruptedException if the current thread is interrupted
438      * @throws NullPointerException if the time unit is null
439      */
440     public boolean tryLock(long timeout, TimeUnit unit)
441             throws InterruptedException {
442         return sync.tryAcquireNanos(1, unit.toNanos(timeout));
443     }
444 
445     /**
446      * Attempts to release this lock.
447      *
448      * <p>If the current thread is the holder of this lock then the hold
449      * count is decremented.  If the hold count is now zero then the lock
450      * is released.  If the current thread is not the holder of this
451      * lock then {@link IllegalMonitorStateException} is thrown.
452      *
453      * @throws IllegalMonitorStateException if the current thread does not
454      *         hold this lock
455      */
456     public void unlock() {
457         sync.release(1);
458     }
459 
460     /**
461      * Returns a {@link Condition} instance for use with this
462      * {@link Lock} instance.
463      *
464      * <p>The returned {@link Condition} instance supports the same
465      * usages as do the {@link Object} monitor methods ({@link
466      * Object#wait() wait}, {@link Object#notify notify}, and {@link
467      * Object#notifyAll notifyAll}) when used with the built-in
468      * monitor lock.
469      *
470      * <ul>
471      *
472      * <li>If this lock is not held when any of the {@link Condition}
473      * {@linkplain Condition#await() waiting} or {@linkplain
474      * Condition#signal signalling} methods are called, then an {@link
475      * IllegalMonitorStateException} is thrown.
476      *
477      * <li>When the condition {@linkplain Condition#await() waiting}
478      * methods are called the lock is released and, before they
479      * return, the lock is reacquired and the lock hold count restored
480      * to what it was when the method was called.
481      *
482      * <li>If a thread is {@linkplain Thread#interrupt interrupted}
483      * while waiting then the wait will terminate, an {@link
484      * InterruptedException} will be thrown, and the thread's
485      * interrupted status will be cleared.
486      *
487      * <li> Waiting threads are signalled in FIFO order.
488      *
489      * <li>The ordering of lock reacquisition for threads returning
490      * from waiting methods is the same as for threads initially
491      * acquiring the lock, which is in the default case not specified,
492      * but for <em>fair</em> locks favors those threads that have been
493      * waiting the longest.
494      *
495      * </ul>
496      *
497      * @return the Condition object
498      */
499     public Condition newCondition() {
500         return sync.newCondition();
501     }
502 
503     /**
504      * Queries the number of holds on this lock by the current thread.
505      *
506      * <p>A thread has a hold on a lock for each lock action that is not
507      * matched by an unlock action.
508      *
509      * <p>The hold count information is typically only used for testing and
510      * debugging purposes. For example, if a certain section of code should
511      * not be entered with the lock already held then we can assert that
512      * fact:
513      *
514      *  <pre> {@code
515      * class X {
516      *   ReentrantLock lock = new ReentrantLock();
517      *   // ...
518      *   public void m() {
519      *     assert lock.getHoldCount() == 0;
520      *     lock.lock();
521      *     try {
522      *       // ... method body
523      *     } finally {
524      *       lock.unlock();
525      *     }
526      *   }
527      * }}</pre>
528      *
529      * @return the number of holds on this lock by the current thread,
530      *         or zero if this lock is not held by the current thread
531      */
532     public int getHoldCount() {
533         return sync.getHoldCount();
534     }
535 
536     /**
537      * Queries if this lock is held by the current thread.
538      *
539      * <p>Analogous to the {@link Thread#holdsLock(Object)} method for
540      * built-in monitor locks, this method is typically used for
541      * debugging and testing. For example, a method that should only be
542      * called while a lock is held can assert that this is the case:
543      *
544      *  <pre> {@code
545      * class X {
546      *   ReentrantLock lock = new ReentrantLock();
547      *   // ...
548      *
549      *   public void m() {
550      *       assert lock.isHeldByCurrentThread();
551      *       // ... method body
552      *   }
553      * }}</pre>
554      *
555      * <p>It can also be used to ensure that a reentrant lock is used
556      * in a non-reentrant manner, for example:
557      *
558      *  <pre> {@code
559      * class X {
560      *   ReentrantLock lock = new ReentrantLock();
561      *   // ...
562      *
563      *   public void m() {
564      *       assert !lock.isHeldByCurrentThread();
565      *       lock.lock();
566      *       try {
567      *           // ... method body
568      *       } finally {
569      *           lock.unlock();
570      *       }
571      *   }
572      * }}</pre>
573      *
574      * @return {@code true} if current thread holds this lock and
575      *         {@code false} otherwise
576      */
577     public boolean isHeldByCurrentThread() {
578         return sync.isHeldExclusively();
579     }
580 
581     /**
582      * Queries if this lock is held by any thread. This method is
583      * designed for use in monitoring of the system state,
584      * not for synchronization control.
585      *
586      * @return {@code true} if any thread holds this lock and
587      *         {@code false} otherwise
588      */
589     public boolean isLocked() {
590         return sync.isLocked();
591     }
592 
593     /**
594      * Returns {@code true} if this lock has fairness set true.
595      *
596      * @return {@code true} if this lock has fairness set true
597      */
598     public final boolean isFair() {
599         return sync instanceof FairSync;
600     }
601 
602     /**
603      * Returns the thread that currently owns this lock, or
604      * {@code null} if not owned. When this method is called by a
605      * thread that is not the owner, the return value reflects a
606      * best-effort approximation of current lock status. For example,
607      * the owner may be momentarily {@code null} even if there are
608      * threads trying to acquire the lock but have not yet done so.
609      * This method is designed to facilitate construction of
610      * subclasses that provide more extensive lock monitoring
611      * facilities.
612      *
613      * @return the owner, or {@code null} if not owned
614      */
615     protected Thread getOwner() {
616         return sync.getOwner();
617     }
618 
619     /**
620      * Queries whether any threads are waiting to acquire this lock. Note that
621      * because cancellations may occur at any time, a {@code true}
622      * return does not guarantee that any other thread will ever
623      * acquire this lock.  This method is designed primarily for use in
624      * monitoring of the system state.
625      *
626      * @return {@code true} if there may be other threads waiting to
627      *         acquire the lock
628      */
629     public final boolean hasQueuedThreads() {
630         return sync.hasQueuedThreads();
631     }
632 
633     /**
634      * Queries whether the given thread is waiting to acquire this
635      * lock. Note that because cancellations may occur at any time, a
636      * {@code true} return does not guarantee that this thread
637      * will ever acquire this lock.  This method is designed primarily for use
638      * in monitoring of the system state.
639      *
640      * @param thread the thread
641      * @return {@code true} if the given thread is queued waiting for this lock
642      * @throws NullPointerException if the thread is null
643      */
644     public final boolean hasQueuedThread(Thread thread) {
645         return sync.isQueued(thread);
646     }
647 
648     /**
649      * Returns an estimate of the number of threads waiting to
650      * acquire this lock.  The value is only an estimate because the number of
651      * threads may change dynamically while this method traverses
652      * internal data structures.  This method is designed for use in
653      * monitoring of the system state, not for synchronization
654      * control.
655      *
656      * @return the estimated number of threads waiting for this lock
657      */
658     public final int getQueueLength() {
659         return sync.getQueueLength();
660     }
661 
662     /**
663      * Returns a collection containing threads that may be waiting to
664      * acquire this lock.  Because the actual set of threads may change
665      * dynamically while constructing this result, the returned
666      * collection is only a best-effort estimate.  The elements of the
667      * returned collection are in no particular order.  This method is
668      * designed to facilitate construction of subclasses that provide
669      * more extensive monitoring facilities.
670      *
671      * @return the collection of threads
672      */
673     protected Collection<Thread> getQueuedThreads() {
674         return sync.getQueuedThreads();
675     }
676 
677     /**
678      * Queries whether any threads are waiting on the given condition
679      * associated with this lock. Note that because timeouts and
680      * interrupts may occur at any time, a {@code true} return does
681      * not guarantee that a future {@code signal} will awaken any
682      * threads.  This method is designed primarily for use in
683      * monitoring of the system state.
684      *
685      * @param condition the condition
686      * @return {@code true} if there are any waiting threads
687      * @throws IllegalMonitorStateException if this lock is not held
688      * @throws IllegalArgumentException if the given condition is
689      *         not associated with this lock
690      * @throws NullPointerException if the condition is null
691      */
692     public boolean hasWaiters(Condition condition) {
693         if (condition == null)
694             throw new NullPointerException();
695         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
696             throw new IllegalArgumentException("not owner");
697         return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
698     }
699 
700     /**
701      * Returns an estimate of the number of threads waiting on the
702      * given condition associated with this lock. Note that because
703      * timeouts and interrupts may occur at any time, the estimate
704      * serves only as an upper bound on the actual number of waiters.
705      * This method is designed for use in monitoring of the system
706      * state, not for synchronization control.
707      *
708      * @param condition the condition
709      * @return the estimated number of waiting threads
710      * @throws IllegalMonitorStateException if this lock is not held
711      * @throws IllegalArgumentException if the given condition is
712      *         not associated with this lock
713      * @throws NullPointerException if the condition is null
714      */
715     public int getWaitQueueLength(Condition condition) {
716         if (condition == null)
717             throw new NullPointerException();
718         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
719             throw new IllegalArgumentException("not owner");
720         return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
721     }
722 
723     /**
724      * Returns a collection containing those threads that may be
725      * waiting on the given condition associated with this lock.
726      * Because the actual set of threads may change dynamically while
727      * constructing this result, the returned collection is only a
728      * best-effort estimate. The elements of the returned collection
729      * are in no particular order.  This method is designed to
730      * facilitate construction of subclasses that provide more
731      * extensive condition monitoring facilities.
732      *
733      * @param condition the condition
734      * @return the collection of threads
735      * @throws IllegalMonitorStateException if this lock is not held
736      * @throws IllegalArgumentException if the given condition is
737      *         not associated with this lock
738      * @throws NullPointerException if the condition is null
739      */
740     protected Collection<Thread> getWaitingThreads(Condition condition) {
741         if (condition == null)
742             throw new NullPointerException();
743         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
744             throw new IllegalArgumentException("not owner");
745         return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
746     }
747 
748     /**
749      * Returns a string identifying this lock, as well as its lock state.
750      * The state, in brackets, includes either the String {@code "Unlocked"}
751      * or the String {@code "Locked by"} followed by the
752      * {@linkplain Thread#getName name} of the owning thread.
753      *
754      * @return a string identifying this lock, as well as its lock state
755      */
756     public String toString() {
757         Thread o = sync.getOwner();
758         return super.toString() + ((o == null) ?
759                                    "[Unlocked]" :
760                                    "[Locked by thread " + o.getName() + "]");
761     }
762 }