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