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