2 * Written by Doug Lea with assistance from members of JCP JSR-166
3 * Expert Group and released to the public domain, as explained at
4 * http://creativecommons.org/licenses/publicdomain
7 /*package java.util.concurrent.locks;
9 import java.util.concurrent.*;
10 import java.util.concurrent.atomic.*;*/
13 * A reentrant mutual exclusion {@link Lock} with the same basic
14 * behavior and semantics as the implicit monitor lock accessed using
15 * {@code synchronized} methods and statements, but with extended
18 * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last
19 * successfully locking, but not yet unlocking it. A thread invoking
20 * {@code lock} will return, successfully acquiring the lock, when
21 * the lock is not owned by another thread. The method will return
22 * immediately if the current thread already owns the lock. This can
23 * be checked using methods {@link #isHeldByCurrentThread}, and {@link
26 * <p>The constructor for this class accepts an optional
27 * <em>fairness</em> parameter. When set {@code true}, under
28 * contention, locks favor granting access to the longest-waiting
29 * thread. Otherwise this lock does not guarantee any particular
30 * access order. Programs using fair locks accessed by many threads
31 * may display lower overall throughput (i.e., are slower; often much
32 * slower) than those using the default setting, but have smaller
33 * variances in times to obtain locks and guarantee lack of
34 * starvation. Note however, that fairness of locks does not guarantee
35 * fairness of thread scheduling. Thus, one of many threads using a
36 * fair lock may obtain it multiple times in succession while other
37 * active threads are not progressing and not currently holding the
39 * Also note that the untimed {@link #tryLock() tryLock} method does not
40 * honor the fairness setting. It will succeed if the lock
41 * is available even if other threads are waiting.
43 * <p>It is recommended practice to <em>always</em> immediately
44 * follow a call to {@code lock} with a {@code try} block, most
45 * typically in a before/after construction such as:
49 * private final ReentrantLock lock = new ReentrantLock();
53 * lock.lock(); // block until condition holds
63 * <p>In addition to implementing the {@link Lock} interface, this
64 * class defines methods {@code isLocked} and
65 * {@code getLockQueueLength}, as well as some associated
66 * {@code protected} access methods that may be useful for
67 * instrumentation and monitoring.
69 * <p>Serialization of this class behaves in the same way as built-in
70 * locks: a deserialized lock is in the unlocked state, regardless of
71 * its state when serialized.
73 * <p>This lock supports a maximum of 2147483647 recursive locks by
74 * the same thread. Attempts to exceed this limit result in
75 * {@link Error} throws from locking methods.
80 public class ReentrantLock implements /*Lock, java.io.*/Serializable {
81 private static final long serialVersionUID = 7373984872572414699L;
82 boolean isLocked = false;
83 Thread lockedBy = null;
86 /** Synchronizer providing all implementation mechanics */
87 //private final Sync sync;
90 * Base of synchronization control for this lock. Subclassed
91 * into fair and nonfair versions below. Uses AQS state to
92 * represent the number of holds on the lock.
94 /*static abstract class Sync extends AbstractQueuedSynchronizer {
95 private static final long serialVersionUID = -5179523762034025860L;
98 * Performs {@link Lock#lock}. The main reason for subclassing
99 * is to allow fast path for nonfair version.
101 /*abstract void lock();
104 * Performs non-fair tryLock. tryAcquire is
105 * implemented in subclasses, but both need nonfair
106 * try for trylock method.
108 /*final boolean nonfairTryAcquire(int acquires) {
109 final Thread current = Thread.currentThread();
112 if (compareAndSetState(0, acquires)) {
113 setExclusiveOwnerThread(current);
117 else if (current == getExclusiveOwnerThread()) {
118 int nextc = c + acquires;
119 if (nextc < 0) // overflow
120 throw new Error("Maximum lock count exceeded");
127 protected final boolean tryRelease(int releases) {
128 int c = getState() - releases;
129 if (Thread.currentThread() != getExclusiveOwnerThread())
130 throw new IllegalMonitorStateException();
131 boolean free = false;
134 setExclusiveOwnerThread(null);
140 protected final boolean isHeldExclusively() {
141 // While we must in general read state before owner,
142 // we don't need to do so to check if current thread is owner
143 return getExclusiveOwnerThread() == Thread.currentThread();
146 final ConditionObject newCondition() {
147 return new ConditionObject();
150 // Methods relayed from outer class
152 final Thread getOwner() {
153 return getState() == 0 ? null : getExclusiveOwnerThread();
156 final int getHoldCount() {
157 return isHeldExclusively() ? getState() : 0;
160 final boolean isLocked() {
161 return getState() != 0;
165 * Reconstitutes this lock instance from a stream.
166 * @param s the stream
168 /*private void readObject(java.io.ObjectInputStream s)
169 throws java.io.IOException, ClassNotFoundException {
170 s.defaultReadObject();
171 setState(0); // reset to unlocked state
176 * Sync object for non-fair locks
178 /*final static class NonfairSync extends Sync {
179 private static final long serialVersionUID = 7316153563782823691L;
182 * Performs lock. Try immediate barge, backing up to normal
183 * acquire on failure.
185 /*final void lock() {
186 if (compareAndSetState(0, 1))
187 setExclusiveOwnerThread(Thread.currentThread());
192 protected final boolean tryAcquire(int acquires) {
193 return nonfairTryAcquire(acquires);
198 * Sync object for fair locks
200 /*final static class FairSync extends Sync {
201 private static final long serialVersionUID = -3000897897090466540L;
208 * Fair version of tryAcquire. Don't grant access unless
209 * recursive call or no waiters or is first.
211 /*protected final boolean tryAcquire(int acquires) {
212 final Thread current = Thread.currentThread();
215 if (isFirst(current) &&
216 compareAndSetState(0, acquires)) {
217 setExclusiveOwnerThread(current);
221 else if (current == getExclusiveOwnerThread()) {
222 int nextc = c + acquires;
224 throw new Error("Maximum lock count exceeded");
233 * Creates an instance of {@code ReentrantLock}.
234 * This is equivalent to using {@code ReentrantLock(false)}.
236 public ReentrantLock() {
237 //sync = new NonfairSync();
241 * Creates an instance of {@code ReentrantLock} with the
242 * given fairness policy.
244 * @param fair {@code true} if this lock should use a fair ordering policy
246 public ReentrantLock(boolean fair) {
247 //sync = (fair)? new FairSync() : new NonfairSync();
253 * <p>Acquires the lock if it is not held by another thread and returns
254 * immediately, setting the lock hold count to one.
256 * <p>If the current thread already holds the lock then the hold
257 * count is incremented by one and the method returns immediately.
259 * <p>If the lock is held by another thread then the
260 * current thread becomes disabled for thread scheduling
261 * purposes and lies dormant until the lock has been acquired,
262 * at which time the lock hold count is set to one.
264 public synchronized void lock() {
266 //System.out.println("Unimplemented ReentrantLock.lock()!");
267 Thread callingThread = Thread.currentThread();
268 while(isLocked && lockedBy != callingThread){
273 lockedBy = callingThread;
277 * Acquires the lock unless the current thread is
278 * {@linkplain Thread#interrupt interrupted}.
280 * <p>Acquires the lock if it is not held by another thread and returns
281 * immediately, setting the lock hold count to one.
283 * <p>If the current thread already holds this lock then the hold count
284 * is incremented by one and the method returns immediately.
286 * <p>If the lock is held by another thread then the
287 * current thread becomes disabled for thread scheduling
288 * purposes and lies dormant until one of two things happens:
292 * <li>The lock is acquired by the current thread; or
294 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
299 * <p>If the lock is acquired by the current thread then the lock hold
300 * count is set to one.
302 * <p>If the current thread:
306 * <li>has its interrupted status set on entry to this method; or
308 * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
313 * then {@link InterruptedException} is thrown and the current thread's
314 * interrupted status is cleared.
316 * <p>In this implementation, as this method is an explicit
317 * interruption point, preference is given to responding to the
318 * interrupt over normal or reentrant acquisition of the lock.
320 * @throws InterruptedException if the current thread is interrupted
322 public void lockInterruptibly() throws InterruptedException {
323 Thread callingThread = Thread.currentThread();
324 while(isLocked && lockedBy != callingThread){
329 lockedBy = callingThread;
330 //System.out.println("Unimplemented ReentrantLock.lockInterruptibly()!");
331 //sync.acquireInterruptibly(1);
335 * Acquires the lock only if it is not held by another thread at the time
338 * <p>Acquires the lock if it is not held by another thread and
339 * returns immediately with the value {@code true}, setting the
340 * lock hold count to one. Even when this lock has been set to use a
341 * fair ordering policy, a call to {@code tryLock()} <em>will</em>
342 * immediately acquire the lock if it is available, whether or not
343 * other threads are currently waiting for the lock.
344 * This "barging" behavior can be useful in certain
345 * circumstances, even though it breaks fairness. If you want to honor
346 * the fairness setting for this lock, then use
347 * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
348 * which is almost equivalent (it also detects interruption).
350 * <p> If the current thread already holds this lock then the hold
351 * count is incremented by one and the method returns {@code true}.
353 * <p>If the lock is held by another thread then this method will return
354 * immediately with the value {@code false}.
356 * @return {@code true} if the lock was free and was acquired by the
357 * current thread, or the lock was already held by the current
358 * thread; and {@code false} otherwise
360 /*public boolean tryLock() {
361 return sync.nonfairTryAcquire(1);
365 * Acquires the lock if it is not held by another thread within the given
366 * waiting time and the current thread has not been
367 * {@linkplain Thread#interrupt interrupted}.
369 * <p>Acquires the lock if it is not held by another thread and returns
370 * immediately with the value {@code true}, setting the lock hold count
371 * to one. If this lock has been set to use a fair ordering policy then
372 * an available lock <em>will not</em> be acquired if any other threads
373 * are waiting for the lock. This is in contrast to the {@link #tryLock()}
374 * method. If you want a timed {@code tryLock} that does permit barging on
375 * a fair lock then combine the timed and un-timed forms together:
377 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
380 * <p>If the current thread
381 * already holds this lock then the hold count is incremented by one and
382 * the method returns {@code true}.
384 * <p>If the lock is held by another thread then the
385 * current thread becomes disabled for thread scheduling
386 * purposes and lies dormant until one of three things happens:
390 * <li>The lock is acquired by the current thread; or
392 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
393 * the current thread; or
395 * <li>The specified waiting time elapses
399 * <p>If the lock is acquired then the value {@code true} is returned and
400 * the lock hold count is set to one.
402 * <p>If the current thread:
406 * <li>has its interrupted status set on entry to this method; or
408 * <li>is {@linkplain Thread#interrupt interrupted} while
409 * acquiring the lock,
412 * then {@link InterruptedException} is thrown and the current thread's
413 * interrupted status is cleared.
415 * <p>If the specified waiting time elapses then the value {@code false}
416 * is returned. If the time is less than or equal to zero, the method
417 * will not wait at all.
419 * <p>In this implementation, as this method is an explicit
420 * interruption point, preference is given to responding to the
421 * interrupt over normal or reentrant acquisition of the lock, and
422 * over reporting the elapse of the waiting time.
424 * @param timeout the time to wait for the lock
425 * @param unit the time unit of the timeout argument
426 * @return {@code true} if the lock was free and was acquired by the
427 * current thread, or the lock was already held by the current
428 * thread; and {@code false} if the waiting time elapsed before
429 * the lock could be acquired
430 * @throws InterruptedException if the current thread is interrupted
431 * @throws NullPointerException if the time unit is null
434 /*public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
435 return sync.tryAcquireNanos(1, unit.toNanos(timeout));
439 * Attempts to release this lock.
441 * <p>If the current thread is the holder of this lock then the hold
442 * count is decremented. If the hold count is now zero then the lock
443 * is released. If the current thread is not the holder of this
444 * lock then {@link IllegalMonitorStateException} is thrown.
446 * @throws IllegalMonitorStateException if the current thread does not
449 public synchronized void unlock() {
451 //System.out.println("Unimplemented ReentrantLock.unlock()!");
452 if(Thread.currentThread() == this.lockedBy){
455 if(lockedCount == 0){
463 * Returns a {@link Condition} instance for use with this
464 * {@link Lock} instance.
466 * <p>The returned {@link Condition} instance supports the same
467 * usages as do the {@link Object} monitor methods ({@link
468 * Object#wait() wait}, {@link Object#notify notify}, and {@link
469 * Object#notifyAll notifyAll}) when used with the built-in
474 * <li>If this lock is not held when any of the {@link Condition}
475 * {@linkplain Condition#await() waiting} or {@linkplain
476 * Condition#signal signalling} methods are called, then an {@link
477 * IllegalMonitorStateException} is thrown.
479 * <li>When the condition {@linkplain Condition#await() waiting}
480 * methods are called the lock is released and, before they
481 * return, the lock is reacquired and the lock hold count restored
482 * to what it was when the method was called.
484 * <li>If a thread is {@linkplain Thread#interrupt interrupted}
485 * while waiting then the wait will terminate, an {@link
486 * InterruptedException} will be thrown, and the thread's
487 * interrupted status will be cleared.
489 * <li> Waiting threads are signalled in FIFO order.
491 * <li>The ordering of lock reacquisition for threads returning
492 * from waiting methods is the same as for threads initially
493 * acquiring the lock, which is in the default case not specified,
494 * but for <em>fair</em> locks favors those threads that have been
495 * waiting the longest.
499 * @return the Condition object
501 public Condition newCondition() {
502 //System.out.println("Unimplemented ReentrantLock.newCondition()!");
504 //return sync.newCondition();
505 return new ConditionObject();
509 * Queries the number of holds on this lock by the current thread.
511 * <p>A thread has a hold on a lock for each lock action that is not
512 * matched by an unlock action.
514 * <p>The hold count information is typically only used for testing and
515 * debugging purposes. For example, if a certain section of code should
516 * not be entered with the lock already held then we can assert that
521 * ReentrantLock lock = new ReentrantLock();
524 * assert lock.getHoldCount() == 0;
535 * @return the number of holds on this lock by the current thread,
536 * or zero if this lock is not held by the current thread
538 /*public int getHoldCount() {
539 return sync.getHoldCount();
543 * Queries if this lock is held by the current thread.
545 * <p>Analogous to the {@link Thread#holdsLock} method for built-in
546 * monitor locks, this method is typically used for debugging and
547 * testing. For example, a method that should only be called while
548 * a lock is held can assert that this is the case:
552 * ReentrantLock lock = new ReentrantLock();
556 * assert lock.isHeldByCurrentThread();
562 * <p>It can also be used to ensure that a reentrant lock is used
563 * in a non-reentrant manner, for example:
567 * ReentrantLock lock = new ReentrantLock();
571 * assert !lock.isHeldByCurrentThread();
582 * @return {@code true} if current thread holds this lock and
583 * {@code false} otherwise
585 /*public boolean isHeldByCurrentThread() {
586 return sync.isHeldExclusively();
590 * Queries if this lock is held by any thread. This method is
591 * designed for use in monitoring of the system state,
592 * not for synchronization control.
594 * @return {@code true} if any thread holds this lock and
595 * {@code false} otherwise
597 /*public boolean isLocked() {
598 return sync.isLocked();
602 * Returns {@code true} if this lock has fairness set true.
604 * @return {@code true} if this lock has fairness set true
606 /*public final boolean isFair() {
607 return sync instanceof FairSync;
611 * Returns the thread that currently owns this lock, or
612 * {@code null} if not owned. When this method is called by a
613 * thread that is not the owner, the return value reflects a
614 * best-effort approximation of current lock status. For example,
615 * the owner may be momentarily {@code null} even if there are
616 * threads trying to acquire the lock but have not yet done so.
617 * This method is designed to facilitate construction of
618 * subclasses that provide more extensive lock monitoring
621 * @return the owner, or {@code null} if not owned
623 /*protected Thread getOwner() {
624 return sync.getOwner();
628 * Queries whether any threads are waiting to acquire this lock. Note that
629 * because cancellations may occur at any time, a {@code true}
630 * return does not guarantee that any other thread will ever
631 * acquire this lock. This method is designed primarily for use in
632 * monitoring of the system state.
634 * @return {@code true} if there may be other threads waiting to
637 /*public final boolean hasQueuedThreads() {
638 return sync.hasQueuedThreads();
643 * Queries whether the given thread is waiting to acquire this
644 * lock. Note that because cancellations may occur at any time, a
645 * {@code true} return does not guarantee that this thread
646 * will ever acquire this lock. This method is designed primarily for use
647 * in monitoring of the system state.
649 * @param thread the thread
650 * @return {@code true} if the given thread is queued waiting for this lock
651 * @throws NullPointerException if the thread is null
653 /*public final boolean hasQueuedThread(Thread thread) {
654 return sync.isQueued(thread);
659 * Returns an estimate of the number of threads waiting to
660 * acquire this lock. The value is only an estimate because the number of
661 * threads may change dynamically while this method traverses
662 * internal data structures. This method is designed for use in
663 * monitoring of the system state, not for synchronization
666 * @return the estimated number of threads waiting for this lock
668 /*public final int getQueueLength() {
669 return sync.getQueueLength();
673 * Returns a collection containing threads that may be waiting to
674 * acquire this lock. Because the actual set of threads may change
675 * dynamically while constructing this result, the returned
676 * collection is only a best-effort estimate. The elements of the
677 * returned collection are in no particular order. This method is
678 * designed to facilitate construction of subclasses that provide
679 * more extensive monitoring facilities.
681 * @return the collection of threads
683 /*protected Collection<Thread> getQueuedThreads() {
684 return sync.getQueuedThreads();
688 * Queries whether any threads are waiting on the given condition
689 * associated with this lock. Note that because timeouts and
690 * interrupts may occur at any time, a {@code true} return does
691 * not guarantee that a future {@code signal} will awaken any
692 * threads. This method is designed primarily for use in
693 * monitoring of the system state.
695 * @param condition the condition
696 * @return {@code true} if there are any waiting threads
697 * @throws IllegalMonitorStateException if this lock is not held
698 * @throws IllegalArgumentException if the given condition is
699 * not associated with this lock
700 * @throws NullPointerException if the condition is null
702 /*public boolean hasWaiters(Condition condition) {
703 if (condition == null)
704 throw new NullPointerException();
705 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
706 throw new IllegalArgumentException("not owner");
707 return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
711 * Returns an estimate of the number of threads waiting on the
712 * given condition associated with this lock. Note that because
713 * timeouts and interrupts may occur at any time, the estimate
714 * serves only as an upper bound on the actual number of waiters.
715 * This method is designed for use in monitoring of the system
716 * state, not for synchronization control.
718 * @param condition the condition
719 * @return the estimated number of waiting threads
720 * @throws IllegalMonitorStateException if this lock is not held
721 * @throws IllegalArgumentException if the given condition is
722 * not associated with this lock
723 * @throws NullPointerException if the condition is null
725 /*public int getWaitQueueLength(Condition condition) {
726 if (condition == null)
727 throw new NullPointerException();
728 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
729 throw new IllegalArgumentException("not owner");
730 return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
734 * Returns a collection containing those threads that may be
735 * waiting on the given condition associated with this lock.
736 * Because the actual set of threads may change dynamically while
737 * constructing this result, the returned collection is only a
738 * best-effort estimate. The elements of the returned collection
739 * are in no particular order. This method is designed to
740 * facilitate construction of subclasses that provide more
741 * extensive condition monitoring facilities.
743 * @param condition the condition
744 * @return the collection of threads
745 * @throws IllegalMonitorStateException if this lock is not held
746 * @throws IllegalArgumentException if the given condition is
747 * not associated with this lock
748 * @throws NullPointerException if the condition is null
750 /*protected Collection<Thread> getWaitingThreads(Condition condition) {
751 if (condition == null)
752 throw new NullPointerException();
753 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
754 throw new IllegalArgumentException("not owner");
755 return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
759 * Returns a string identifying this lock, as well as its lock state.
760 * The state, in brackets, includes either the String {@code "Unlocked"}
761 * or the String {@code "Locked by"} followed by the
762 * {@linkplain Thread#getName name} of the owning thread.
764 * @return a string identifying this lock, as well as its lock state
766 /*public String toString() {
767 Thread o = sync.getOwner();
768 return super.toString() + ((o == null) ?
770 "[Locked by thread " + o.getName() + "]");