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. 123 */ 124 @ReservedStackAccess tryLock()125 final boolean tryLock() { 126 Thread current = Thread.currentThread(); 127 int c = getState(); 128 if (c == 0) { 129 if (compareAndSetState(0, 1)) { 130 setExclusiveOwnerThread(current); 131 return true; 132 } 133 } else if (getExclusiveOwnerThread() == current) { 134 if (++c < 0) // overflow 135 throw new Error("Maximum lock count exceeded"); 136 setState(c); 137 return true; 138 } 139 return false; 140 } 141 142 /** 143 * Checks for reentrancy and acquires if lock immediately 144 * available under fair vs nonfair rules. Locking methods 145 * perform initialTryLock check before relaying to 146 * corresponding AQS acquire methods. 147 */ initialTryLock()148 abstract boolean initialTryLock(); 149 150 @ReservedStackAccess lock()151 final void lock() { 152 if (!initialTryLock()) 153 acquire(1); 154 } 155 156 @ReservedStackAccess lockInterruptibly()157 final void lockInterruptibly() throws InterruptedException { 158 if (Thread.interrupted()) 159 throw new InterruptedException(); 160 if (!initialTryLock()) 161 acquireInterruptibly(1); 162 } 163 164 @ReservedStackAccess tryLockNanos(long nanos)165 final boolean tryLockNanos(long nanos) throws InterruptedException { 166 if (Thread.interrupted()) 167 throw new InterruptedException(); 168 return initialTryLock() || tryAcquireNanos(1, nanos); 169 } 170 171 @ReservedStackAccess tryRelease(int releases)172 protected final boolean tryRelease(int releases) { 173 int c = getState() - releases; 174 if (getExclusiveOwnerThread() != Thread.currentThread()) 175 throw new IllegalMonitorStateException(); 176 boolean free = (c == 0); 177 if (free) 178 setExclusiveOwnerThread(null); 179 setState(c); 180 return free; 181 } 182 isHeldExclusively()183 protected final boolean isHeldExclusively() { 184 // While we must in general read state before owner, 185 // we don't need to do so to check if current thread is owner 186 return getExclusiveOwnerThread() == Thread.currentThread(); 187 } 188 newCondition()189 final ConditionObject newCondition() { 190 return new ConditionObject(); 191 } 192 193 // Methods relayed from outer class 194 getOwner()195 final Thread getOwner() { 196 return getState() == 0 ? null : getExclusiveOwnerThread(); 197 } 198 getHoldCount()199 final int getHoldCount() { 200 return isHeldExclusively() ? getState() : 0; 201 } 202 isLocked()203 final boolean isLocked() { 204 return getState() != 0; 205 } 206 207 /** 208 * Reconstitutes the instance from a stream (that is, deserializes it). 209 */ readObject(java.io.ObjectInputStream s)210 private void readObject(java.io.ObjectInputStream s) 211 throws java.io.IOException, ClassNotFoundException { 212 s.defaultReadObject(); 213 setState(0); // reset to unlocked state 214 } 215 } 216 217 /** 218 * Sync object for non-fair locks 219 */ 220 static final class NonfairSync extends Sync { 221 private static final long serialVersionUID = 7316153563782823691L; 222 initialTryLock()223 final boolean initialTryLock() { 224 Thread current = Thread.currentThread(); 225 if (compareAndSetState(0, 1)) { // first attempt is unguarded 226 setExclusiveOwnerThread(current); 227 return true; 228 } else if (getExclusiveOwnerThread() == current) { 229 int c = getState() + 1; 230 if (c < 0) // overflow 231 throw new Error("Maximum lock count exceeded"); 232 setState(c); 233 return true; 234 } else 235 return false; 236 } 237 238 /** 239 * Acquire for non-reentrant cases after initialTryLock prescreen 240 */ tryAcquire(int acquires)241 protected final boolean tryAcquire(int acquires) { 242 if (getState() == 0 && compareAndSetState(0, acquires)) { 243 setExclusiveOwnerThread(Thread.currentThread()); 244 return true; 245 } 246 return false; 247 } 248 } 249 250 /** 251 * Sync object for fair locks 252 */ 253 static final class FairSync extends Sync { 254 private static final long serialVersionUID = -3000897897090466540L; 255 256 /** 257 * Acquires only if reentrant or queue is empty. 258 */ initialTryLock()259 final boolean initialTryLock() { 260 Thread current = Thread.currentThread(); 261 int c = getState(); 262 if (c == 0) { 263 if (!hasQueuedThreads() && compareAndSetState(0, 1)) { 264 setExclusiveOwnerThread(current); 265 return true; 266 } 267 } else if (getExclusiveOwnerThread() == current) { 268 if (++c < 0) // overflow 269 throw new Error("Maximum lock count exceeded"); 270 setState(c); 271 return true; 272 } 273 return false; 274 } 275 276 /** 277 * Acquires only if thread is first waiter or empty 278 */ tryAcquire(int acquires)279 protected final boolean tryAcquire(int acquires) { 280 if (getState() == 0 && !hasQueuedPredecessors() && 281 compareAndSetState(0, acquires)) { 282 setExclusiveOwnerThread(Thread.currentThread()); 283 return true; 284 } 285 return false; 286 } 287 } 288 289 /** 290 * Creates an instance of {@code ReentrantLock}. 291 * This is equivalent to using {@code ReentrantLock(false)}. 292 */ ReentrantLock()293 public ReentrantLock() { 294 sync = new NonfairSync(); 295 } 296 297 /** 298 * Creates an instance of {@code ReentrantLock} with the 299 * given fairness policy. 300 * 301 * @param fair {@code true} if this lock should use a fair ordering policy 302 */ ReentrantLock(boolean fair)303 public ReentrantLock(boolean fair) { 304 sync = fair ? new FairSync() : new NonfairSync(); 305 } 306 307 /** 308 * Acquires the lock. 309 * 310 * <p>Acquires the lock if it is not held by another thread and returns 311 * immediately, setting the lock hold count to one. 312 * 313 * <p>If the current thread already holds the lock then the hold 314 * count is incremented by one and the method returns immediately. 315 * 316 * <p>If the lock is held by another thread then the 317 * current thread becomes disabled for thread scheduling 318 * purposes and lies dormant until the lock has been acquired, 319 * at which time the lock hold count is set to one. 320 */ lock()321 public void lock() { 322 sync.lock(); 323 } 324 325 /** 326 * Acquires the lock unless the current thread is 327 * {@linkplain Thread#interrupt interrupted}. 328 * 329 * <p>Acquires the lock if it is not held by another thread and returns 330 * immediately, setting the lock hold count to one. 331 * 332 * <p>If the current thread already holds this lock then the hold count 333 * is incremented by one and the method returns immediately. 334 * 335 * <p>If the lock is held by another thread then the 336 * current thread becomes disabled for thread scheduling 337 * purposes and lies dormant until one of two things happens: 338 * 339 * <ul> 340 * 341 * <li>The lock is acquired by the current thread; or 342 * 343 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the 344 * current thread. 345 * 346 * </ul> 347 * 348 * <p>If the lock is acquired by the current thread then the lock hold 349 * count is set to one. 350 * 351 * <p>If the current thread: 352 * 353 * <ul> 354 * 355 * <li>has its interrupted status set on entry to this method; or 356 * 357 * <li>is {@linkplain Thread#interrupt interrupted} while acquiring 358 * the lock, 359 * 360 * </ul> 361 * 362 * then {@link InterruptedException} is thrown and the current thread's 363 * interrupted status is cleared. 364 * 365 * <p>In this implementation, as this method is an explicit 366 * interruption point, preference is given to responding to the 367 * interrupt over normal or reentrant acquisition of the lock. 368 * 369 * @throws InterruptedException if the current thread is interrupted 370 */ lockInterruptibly()371 public void lockInterruptibly() throws InterruptedException { 372 sync.lockInterruptibly(); 373 } 374 375 /** 376 * Acquires the lock only if it is not held by another thread at the time 377 * of invocation. 378 * 379 * <p>Acquires the lock if it is not held by another thread and 380 * returns immediately with the value {@code true}, setting the 381 * lock hold count to one. Even when this lock has been set to use a 382 * fair ordering policy, a call to {@code tryLock()} <em>will</em> 383 * immediately acquire the lock if it is available, whether or not 384 * other threads are currently waiting for the lock. 385 * This "barging" behavior can be useful in certain 386 * circumstances, even though it breaks fairness. If you want to honor 387 * the fairness setting for this lock, then use 388 * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS)} 389 * which is almost equivalent (it also detects interruption). 390 * 391 * <p>If the current thread already holds this lock then the hold 392 * count is incremented by one and the method returns {@code true}. 393 * 394 * <p>If the lock is held by another thread then this method will return 395 * immediately with the value {@code false}. 396 * 397 * @return {@code true} if the lock was free and was acquired by the 398 * current thread, or the lock was already held by the current 399 * thread; and {@code false} otherwise 400 */ tryLock()401 public boolean tryLock() { 402 return sync.tryLock(); 403 } 404 405 /** 406 * Acquires the lock if it is not held by another thread within the given 407 * waiting time and the current thread has not been 408 * {@linkplain Thread#interrupt interrupted}. 409 * 410 * <p>Acquires the lock if it is not held by another thread and returns 411 * immediately with the value {@code true}, setting the lock hold count 412 * to one. If this lock has been set to use a fair ordering policy then 413 * an available lock <em>will not</em> be acquired if any other threads 414 * are waiting for the lock. This is in contrast to the {@link #tryLock()} 415 * method. If you want a timed {@code tryLock} that does permit barging on 416 * a fair lock then combine the timed and un-timed forms together: 417 * 418 * <pre> {@code 419 * if (lock.tryLock() || 420 * lock.tryLock(timeout, unit)) { 421 * ... 422 * }}</pre> 423 * 424 * <p>If the current thread 425 * already holds this lock then the hold count is incremented by one and 426 * the method returns {@code true}. 427 * 428 * <p>If the lock is held by another thread then the 429 * current thread becomes disabled for thread scheduling 430 * purposes and lies dormant until one of three things happens: 431 * 432 * <ul> 433 * 434 * <li>The lock is acquired by the current thread; or 435 * 436 * <li>Some other thread {@linkplain Thread#interrupt interrupts} 437 * the current thread; or 438 * 439 * <li>The specified waiting time elapses 440 * 441 * </ul> 442 * 443 * <p>If the lock is acquired then the value {@code true} is returned and 444 * the lock hold count is set to one. 445 * 446 * <p>If the current thread: 447 * 448 * <ul> 449 * 450 * <li>has its interrupted status set on entry to this method; or 451 * 452 * <li>is {@linkplain Thread#interrupt interrupted} while 453 * acquiring the lock, 454 * 455 * </ul> 456 * then {@link InterruptedException} is thrown and the current thread's 457 * interrupted status is cleared. 458 * 459 * <p>If the specified waiting time elapses then the value {@code false} 460 * is returned. If the time is less than or equal to zero, the method 461 * will not wait at all. 462 * 463 * <p>In this implementation, as this method is an explicit 464 * interruption point, preference is given to responding to the 465 * interrupt over normal or reentrant acquisition of the lock, and 466 * over reporting the elapse of the waiting time. 467 * 468 * @param timeout the time to wait for the lock 469 * @param unit the time unit of the timeout argument 470 * @return {@code true} if the lock was free and was acquired by the 471 * current thread, or the lock was already held by the current 472 * thread; and {@code false} if the waiting time elapsed before 473 * the lock could be acquired 474 * @throws InterruptedException if the current thread is interrupted 475 * @throws NullPointerException if the time unit is null 476 */ tryLock(long timeout, TimeUnit unit)477 public boolean tryLock(long timeout, TimeUnit unit) 478 throws InterruptedException { 479 return sync.tryLockNanos(unit.toNanos(timeout)); 480 } 481 482 /** 483 * Attempts to release this lock. 484 * 485 * <p>If the current thread is the holder of this lock then the hold 486 * count is decremented. If the hold count is now zero then the lock 487 * is released. If the current thread is not the holder of this 488 * lock then {@link IllegalMonitorStateException} is thrown. 489 * 490 * @throws IllegalMonitorStateException if the current thread does not 491 * hold this lock 492 */ unlock()493 public void unlock() { 494 sync.release(1); 495 } 496 497 /** 498 * Returns a {@link Condition} instance for use with this 499 * {@link Lock} instance. 500 * 501 * <p>The returned {@link Condition} instance supports the same 502 * usages as do the {@link Object} monitor methods ({@link 503 * Object#wait() wait}, {@link Object#notify notify}, and {@link 504 * Object#notifyAll notifyAll}) when used with the built-in 505 * monitor lock. 506 * 507 * <ul> 508 * 509 * <li>If this lock is not held when any of the {@link Condition} 510 * {@linkplain Condition#await() waiting} or {@linkplain 511 * Condition#signal signalling} methods are called, then an {@link 512 * IllegalMonitorStateException} is thrown. 513 * 514 * <li>When the condition {@linkplain Condition#await() waiting} 515 * methods are called the lock is released and, before they 516 * return, the lock is reacquired and the lock hold count restored 517 * to what it was when the method was called. 518 * 519 * <li>If a thread is {@linkplain Thread#interrupt interrupted} 520 * while waiting then the wait will terminate, an {@link 521 * InterruptedException} will be thrown, and the thread's 522 * interrupted status will be cleared. 523 * 524 * <li>Waiting threads are signalled in FIFO order. 525 * 526 * <li>The ordering of lock reacquisition for threads returning 527 * from waiting methods is the same as for threads initially 528 * acquiring the lock, which is in the default case not specified, 529 * but for <em>fair</em> locks favors those threads that have been 530 * waiting the longest. 531 * 532 * </ul> 533 * 534 * @return the Condition object 535 */ newCondition()536 public Condition newCondition() { 537 return sync.newCondition(); 538 } 539 540 /** 541 * Queries the number of holds on this lock by the current thread. 542 * 543 * <p>A thread has a hold on a lock for each lock action that is not 544 * matched by an unlock action. 545 * 546 * <p>The hold count information is typically only used for testing and 547 * debugging purposes. For example, if a certain section of code should 548 * not be entered with the lock already held then we can assert that 549 * fact: 550 * 551 * <pre> {@code 552 * class X { 553 * final ReentrantLock lock = new ReentrantLock(); 554 * // ... 555 * public void m() { 556 * assert lock.getHoldCount() == 0; 557 * lock.lock(); 558 * try { 559 * // ... method body 560 * } finally { 561 * lock.unlock(); 562 * } 563 * } 564 * }}</pre> 565 * 566 * @return the number of holds on this lock by the current thread, 567 * or zero if this lock is not held by the current thread 568 */ getHoldCount()569 public int getHoldCount() { 570 return sync.getHoldCount(); 571 } 572 573 /** 574 * Queries if this lock is held by the current thread. 575 * 576 * <p>Analogous to the {@link Thread#holdsLock(Object)} method for 577 * built-in monitor locks, this method is typically used for 578 * debugging and testing. For example, a method that should only be 579 * called while a lock is held can assert that this is the case: 580 * 581 * <pre> {@code 582 * class X { 583 * final ReentrantLock lock = new ReentrantLock(); 584 * // ... 585 * 586 * public void m() { 587 * assert lock.isHeldByCurrentThread(); 588 * // ... method body 589 * } 590 * }}</pre> 591 * 592 * <p>It can also be used to ensure that a reentrant lock is used 593 * in a non-reentrant manner, for example: 594 * 595 * <pre> {@code 596 * class X { 597 * final ReentrantLock lock = new ReentrantLock(); 598 * // ... 599 * 600 * public void m() { 601 * assert !lock.isHeldByCurrentThread(); 602 * lock.lock(); 603 * try { 604 * // ... method body 605 * } finally { 606 * lock.unlock(); 607 * } 608 * } 609 * }}</pre> 610 * 611 * @return {@code true} if current thread holds this lock and 612 * {@code false} otherwise 613 */ isHeldByCurrentThread()614 public boolean isHeldByCurrentThread() { 615 return sync.isHeldExclusively(); 616 } 617 618 /** 619 * Queries if this lock is held by any thread. This method is 620 * designed for use in monitoring of the system state, 621 * not for synchronization control. 622 * 623 * @return {@code true} if any thread holds this lock and 624 * {@code false} otherwise 625 */ isLocked()626 public boolean isLocked() { 627 return sync.isLocked(); 628 } 629 630 /** 631 * Returns {@code true} if this lock has fairness set true. 632 * 633 * @return {@code true} if this lock has fairness set true 634 */ isFair()635 public final boolean isFair() { 636 return sync instanceof FairSync; 637 } 638 639 /** 640 * Returns the thread that currently owns this lock, or 641 * {@code null} if not owned. When this method is called by a 642 * thread that is not the owner, the return value reflects a 643 * best-effort approximation of current lock status. For example, 644 * the owner may be momentarily {@code null} even if there are 645 * threads trying to acquire the lock but have not yet done so. 646 * This method is designed to facilitate construction of 647 * subclasses that provide more extensive lock monitoring 648 * facilities. 649 * 650 * @return the owner, or {@code null} if not owned 651 */ getOwner()652 protected Thread getOwner() { 653 return sync.getOwner(); 654 } 655 656 /** 657 * Queries whether any threads are waiting to acquire this lock. Note that 658 * because cancellations may occur at any time, a {@code true} 659 * return does not guarantee that any other thread will ever 660 * acquire this lock. This method is designed primarily for use in 661 * monitoring of the system state. 662 * 663 * @return {@code true} if there may be other threads waiting to 664 * acquire the lock 665 */ hasQueuedThreads()666 public final boolean hasQueuedThreads() { 667 return sync.hasQueuedThreads(); 668 } 669 670 /** 671 * Queries whether the given thread is waiting to acquire this 672 * lock. Note that because cancellations may occur at any time, a 673 * {@code true} return does not guarantee that this thread 674 * will ever acquire this lock. This method is designed primarily for use 675 * in monitoring of the system state. 676 * 677 * @param thread the thread 678 * @return {@code true} if the given thread is queued waiting for this lock 679 * @throws NullPointerException if the thread is null 680 */ hasQueuedThread(Thread thread)681 public final boolean hasQueuedThread(Thread thread) { 682 return sync.isQueued(thread); 683 } 684 685 /** 686 * Returns an estimate of the number of threads waiting to acquire 687 * this lock. The value is only an estimate because the number of 688 * threads may change dynamically while this method traverses 689 * internal data structures. This method is designed for use in 690 * monitoring system state, not for synchronization control. 691 * 692 * @return the estimated number of threads waiting for this lock 693 */ getQueueLength()694 public final int getQueueLength() { 695 return sync.getQueueLength(); 696 } 697 698 /** 699 * Returns a collection containing threads that may be waiting to 700 * acquire this lock. Because the actual set of threads may change 701 * dynamically while constructing this result, the returned 702 * collection is only a best-effort estimate. The elements of the 703 * returned collection are in no particular order. This method is 704 * designed to facilitate construction of subclasses that provide 705 * more extensive monitoring facilities. 706 * 707 * @return the collection of threads 708 */ getQueuedThreads()709 protected Collection<Thread> getQueuedThreads() { 710 return sync.getQueuedThreads(); 711 } 712 713 /** 714 * Queries whether any threads are waiting on the given condition 715 * associated with this lock. Note that because timeouts and 716 * interrupts may occur at any time, a {@code true} return does 717 * not guarantee that a future {@code signal} will awaken any 718 * threads. This method is designed primarily for use in 719 * monitoring of the system state. 720 * 721 * @param condition the condition 722 * @return {@code true} if there are any waiting threads 723 * @throws IllegalMonitorStateException if this lock is not held 724 * @throws IllegalArgumentException if the given condition is 725 * not associated with this lock 726 * @throws NullPointerException if the condition is null 727 */ hasWaiters(Condition condition)728 public boolean hasWaiters(Condition condition) { 729 if (condition == null) 730 throw new NullPointerException(); 731 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 732 throw new IllegalArgumentException("not owner"); 733 return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition); 734 } 735 736 /** 737 * Returns an estimate of the number of threads waiting on the 738 * given condition associated with this lock. Note that because 739 * timeouts and interrupts may occur at any time, the estimate 740 * serves only as an upper bound on the actual number of waiters. 741 * This method is designed for use in monitoring of the system 742 * state, not for synchronization control. 743 * 744 * @param condition the condition 745 * @return the estimated number of waiting threads 746 * @throws IllegalMonitorStateException if this lock is not held 747 * @throws IllegalArgumentException if the given condition is 748 * not associated with this lock 749 * @throws NullPointerException if the condition is null 750 */ getWaitQueueLength(Condition condition)751 public int getWaitQueueLength(Condition condition) { 752 if (condition == null) 753 throw new NullPointerException(); 754 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 755 throw new IllegalArgumentException("not owner"); 756 return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition); 757 } 758 759 /** 760 * Returns a collection containing those threads that may be 761 * waiting on the given condition associated with this lock. 762 * Because the actual set of threads may change dynamically while 763 * constructing this result, the returned collection is only a 764 * best-effort estimate. The elements of the returned collection 765 * are in no particular order. This method is designed to 766 * facilitate construction of subclasses that provide more 767 * extensive condition monitoring facilities. 768 * 769 * @param condition the condition 770 * @return the collection of threads 771 * @throws IllegalMonitorStateException if this lock is not held 772 * @throws IllegalArgumentException if the given condition is 773 * not associated with this lock 774 * @throws NullPointerException if the condition is null 775 */ getWaitingThreads(Condition condition)776 protected Collection<Thread> getWaitingThreads(Condition condition) { 777 if (condition == null) 778 throw new NullPointerException(); 779 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject)) 780 throw new IllegalArgumentException("not owner"); 781 return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition); 782 } 783 784 /** 785 * Returns a string identifying this lock, as well as its lock state. 786 * The state, in brackets, includes either the String {@code "Unlocked"} 787 * or the String {@code "Locked by"} followed by the 788 * {@linkplain Thread#getName name} of the owning thread. 789 * 790 * @return a string identifying this lock, as well as its lock state 791 */ toString()792 public String toString() { 793 Thread o = sync.getOwner(); 794 return super.toString() + ((o == null) ? 795 "[Unlocked]" : 796 "[Locked by thread " + o.getName() + "]"); 797 } 798 } 799