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 /** Synchronizer providing all implementation mechanics */
83 //private final Sync sync;
86 * Base of synchronization control for this lock. Subclassed
87 * into fair and nonfair versions below. Uses AQS state to
88 * represent the number of holds on the lock.
90 /*static abstract class Sync extends AbstractQueuedSynchronizer {
91 private static final long serialVersionUID = -5179523762034025860L;
94 * Performs {@link Lock#lock}. The main reason for subclassing
95 * is to allow fast path for nonfair version.
97 /*abstract void lock();
100 * Performs non-fair tryLock. tryAcquire is
101 * implemented in subclasses, but both need nonfair
102 * try for trylock method.
104 /*final boolean nonfairTryAcquire(int acquires) {
105 final Thread current = Thread.currentThread();
108 if (compareAndSetState(0, acquires)) {
109 setExclusiveOwnerThread(current);
113 else if (current == getExclusiveOwnerThread()) {
114 int nextc = c + acquires;
115 if (nextc < 0) // overflow
116 throw new Error("Maximum lock count exceeded");
123 protected final boolean tryRelease(int releases) {
124 int c = getState() - releases;
125 if (Thread.currentThread() != getExclusiveOwnerThread())
126 throw new IllegalMonitorStateException();
127 boolean free = false;
130 setExclusiveOwnerThread(null);
136 protected final boolean isHeldExclusively() {
137 // While we must in general read state before owner,
138 // we don't need to do so to check if current thread is owner
139 return getExclusiveOwnerThread() == Thread.currentThread();
142 final ConditionObject newCondition() {
143 return new ConditionObject();
146 // Methods relayed from outer class
148 final Thread getOwner() {
149 return getState() == 0 ? null : getExclusiveOwnerThread();
152 final int getHoldCount() {
153 return isHeldExclusively() ? getState() : 0;
156 final boolean isLocked() {
157 return getState() != 0;
161 * Reconstitutes this lock instance from a stream.
162 * @param s the stream
164 /*private void readObject(java.io.ObjectInputStream s)
165 throws java.io.IOException, ClassNotFoundException {
166 s.defaultReadObject();
167 setState(0); // reset to unlocked state
172 * Sync object for non-fair locks
174 /*final static class NonfairSync extends Sync {
175 private static final long serialVersionUID = 7316153563782823691L;
178 * Performs lock. Try immediate barge, backing up to normal
179 * acquire on failure.
181 /*final void lock() {
182 if (compareAndSetState(0, 1))
183 setExclusiveOwnerThread(Thread.currentThread());
188 protected final boolean tryAcquire(int acquires) {
189 return nonfairTryAcquire(acquires);
194 * Sync object for fair locks
196 /*final static class FairSync extends Sync {
197 private static final long serialVersionUID = -3000897897090466540L;
204 * Fair version of tryAcquire. Don't grant access unless
205 * recursive call or no waiters or is first.
207 /*protected final boolean tryAcquire(int acquires) {
208 final Thread current = Thread.currentThread();
211 if (isFirst(current) &&
212 compareAndSetState(0, acquires)) {
213 setExclusiveOwnerThread(current);
217 else if (current == getExclusiveOwnerThread()) {
218 int nextc = c + acquires;
220 throw new Error("Maximum lock count exceeded");
229 * Creates an instance of {@code ReentrantLock}.
230 * This is equivalent to using {@code ReentrantLock(false)}.
232 public ReentrantLock() {
233 //sync = new NonfairSync();
237 * Creates an instance of {@code ReentrantLock} with the
238 * given fairness policy.
240 * @param fair {@code true} if this lock should use a fair ordering policy
242 public ReentrantLock(boolean fair) {
243 //sync = (fair)? new FairSync() : new NonfairSync();
249 * <p>Acquires the lock if it is not held by another thread and returns
250 * immediately, setting the lock hold count to one.
252 * <p>If the current thread already holds the lock then the hold
253 * count is incremented by one and the method returns immediately.
255 * <p>If the lock is held by another thread then the
256 * current thread becomes disabled for thread scheduling
257 * purposes and lies dormant until the lock has been acquired,
258 * at which time the lock hold count is set to one.
262 System.out.println("Unimplemented ReentrantLock.lock()!");
266 * Acquires the lock unless the current thread is
267 * {@linkplain Thread#interrupt interrupted}.
269 * <p>Acquires the lock if it is not held by another thread and returns
270 * immediately, setting the lock hold count to one.
272 * <p>If the current thread already holds this lock then the hold count
273 * is incremented by one and the method returns immediately.
275 * <p>If the lock is held by another thread then the
276 * current thread becomes disabled for thread scheduling
277 * purposes and lies dormant until one of two things happens:
281 * <li>The lock is acquired by the current thread; or
283 * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
288 * <p>If the lock is acquired by the current thread then the lock hold
289 * count is set to one.
291 * <p>If the current thread:
295 * <li>has its interrupted status set on entry to this method; or
297 * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
302 * then {@link InterruptedException} is thrown and the current thread's
303 * interrupted status is cleared.
305 * <p>In this implementation, as this method is an explicit
306 * interruption point, preference is given to responding to the
307 * interrupt over normal or reentrant acquisition of the lock.
309 * @throws InterruptedException if the current thread is interrupted
311 /*public void lockInterruptibly() throws InterruptedException {
312 sync.acquireInterruptibly(1);
316 * Acquires the lock only if it is not held by another thread at the time
319 * <p>Acquires the lock if it is not held by another thread and
320 * returns immediately with the value {@code true}, setting the
321 * lock hold count to one. Even when this lock has been set to use a
322 * fair ordering policy, a call to {@code tryLock()} <em>will</em>
323 * immediately acquire the lock if it is available, whether or not
324 * other threads are currently waiting for the lock.
325 * This "barging" behavior can be useful in certain
326 * circumstances, even though it breaks fairness. If you want to honor
327 * the fairness setting for this lock, then use
328 * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
329 * which is almost equivalent (it also detects interruption).
331 * <p> If the current thread already holds this lock then the hold
332 * count is incremented by one and the method returns {@code true}.
334 * <p>If the lock is held by another thread then this method will return
335 * immediately with the value {@code false}.
337 * @return {@code true} if the lock was free and was acquired by the
338 * current thread, or the lock was already held by the current
339 * thread; and {@code false} otherwise
341 /*public boolean tryLock() {
342 return sync.nonfairTryAcquire(1);
346 * Acquires the lock if it is not held by another thread within the given
347 * waiting time and the current thread has not been
348 * {@linkplain Thread#interrupt interrupted}.
350 * <p>Acquires the lock if it is not held by another thread and returns
351 * immediately with the value {@code true}, setting the lock hold count
352 * to one. If this lock has been set to use a fair ordering policy then
353 * an available lock <em>will not</em> be acquired if any other threads
354 * are waiting for the lock. This is in contrast to the {@link #tryLock()}
355 * method. If you want a timed {@code tryLock} that does permit barging on
356 * a fair lock then combine the timed and un-timed forms together:
358 * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
361 * <p>If the current thread
362 * already holds this lock then the hold count is incremented by one and
363 * the method returns {@code true}.
365 * <p>If the lock is held by another thread then the
366 * current thread becomes disabled for thread scheduling
367 * purposes and lies dormant until one of three things happens:
371 * <li>The lock is acquired by the current thread; or
373 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
374 * the current thread; or
376 * <li>The specified waiting time elapses
380 * <p>If the lock is acquired then the value {@code true} is returned and
381 * the lock hold count is set to one.
383 * <p>If the current thread:
387 * <li>has its interrupted status set on entry to this method; or
389 * <li>is {@linkplain Thread#interrupt interrupted} while
390 * acquiring the lock,
393 * then {@link InterruptedException} is thrown and the current thread's
394 * interrupted status is cleared.
396 * <p>If the specified waiting time elapses then the value {@code false}
397 * is returned. If the time is less than or equal to zero, the method
398 * will not wait at all.
400 * <p>In this implementation, as this method is an explicit
401 * interruption point, preference is given to responding to the
402 * interrupt over normal or reentrant acquisition of the lock, and
403 * over reporting the elapse of the waiting time.
405 * @param timeout the time to wait for the lock
406 * @param unit the time unit of the timeout argument
407 * @return {@code true} if the lock was free and was acquired by the
408 * current thread, or the lock was already held by the current
409 * thread; and {@code false} if the waiting time elapsed before
410 * the lock could be acquired
411 * @throws InterruptedException if the current thread is interrupted
412 * @throws NullPointerException if the time unit is null
415 /*public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException {
416 return sync.tryAcquireNanos(1, unit.toNanos(timeout));
420 * Attempts to release this lock.
422 * <p>If the current thread is the holder of this lock then the hold
423 * count is decremented. If the hold count is now zero then the lock
424 * is released. If the current thread is not the holder of this
425 * lock then {@link IllegalMonitorStateException} is thrown.
427 * @throws IllegalMonitorStateException if the current thread does not
430 public void unlock() {
432 System.out.println("Unimplemented ReentrantLock.unlock()!");
436 * Returns a {@link Condition} instance for use with this
437 * {@link Lock} instance.
439 * <p>The returned {@link Condition} instance supports the same
440 * usages as do the {@link Object} monitor methods ({@link
441 * Object#wait() wait}, {@link Object#notify notify}, and {@link
442 * Object#notifyAll notifyAll}) when used with the built-in
447 * <li>If this lock is not held when any of the {@link Condition}
448 * {@linkplain Condition#await() waiting} or {@linkplain
449 * Condition#signal signalling} methods are called, then an {@link
450 * IllegalMonitorStateException} is thrown.
452 * <li>When the condition {@linkplain Condition#await() waiting}
453 * methods are called the lock is released and, before they
454 * return, the lock is reacquired and the lock hold count restored
455 * to what it was when the method was called.
457 * <li>If a thread is {@linkplain Thread#interrupt interrupted}
458 * while waiting then the wait will terminate, an {@link
459 * InterruptedException} will be thrown, and the thread's
460 * interrupted status will be cleared.
462 * <li> Waiting threads are signalled in FIFO order.
464 * <li>The ordering of lock reacquisition for threads returning
465 * from waiting methods is the same as for threads initially
466 * acquiring the lock, which is in the default case not specified,
467 * but for <em>fair</em> locks favors those threads that have been
468 * waiting the longest.
472 * @return the Condition object
474 public Condition newCondition() {
475 System.out.println("Unimplemented ReentrantLock.newCondition()!");
477 //return sync.newCondition();
481 * Queries the number of holds on this lock by the current thread.
483 * <p>A thread has a hold on a lock for each lock action that is not
484 * matched by an unlock action.
486 * <p>The hold count information is typically only used for testing and
487 * debugging purposes. For example, if a certain section of code should
488 * not be entered with the lock already held then we can assert that
493 * ReentrantLock lock = new ReentrantLock();
496 * assert lock.getHoldCount() == 0;
507 * @return the number of holds on this lock by the current thread,
508 * or zero if this lock is not held by the current thread
510 /*public int getHoldCount() {
511 return sync.getHoldCount();
515 * Queries if this lock is held by the current thread.
517 * <p>Analogous to the {@link Thread#holdsLock} method for built-in
518 * monitor locks, this method is typically used for debugging and
519 * testing. For example, a method that should only be called while
520 * a lock is held can assert that this is the case:
524 * ReentrantLock lock = new ReentrantLock();
528 * assert lock.isHeldByCurrentThread();
534 * <p>It can also be used to ensure that a reentrant lock is used
535 * in a non-reentrant manner, for example:
539 * ReentrantLock lock = new ReentrantLock();
543 * assert !lock.isHeldByCurrentThread();
554 * @return {@code true} if current thread holds this lock and
555 * {@code false} otherwise
557 /*public boolean isHeldByCurrentThread() {
558 return sync.isHeldExclusively();
562 * Queries if this lock is held by any thread. This method is
563 * designed for use in monitoring of the system state,
564 * not for synchronization control.
566 * @return {@code true} if any thread holds this lock and
567 * {@code false} otherwise
569 /*public boolean isLocked() {
570 return sync.isLocked();
574 * Returns {@code true} if this lock has fairness set true.
576 * @return {@code true} if this lock has fairness set true
578 /*public final boolean isFair() {
579 return sync instanceof FairSync;
583 * Returns the thread that currently owns this lock, or
584 * {@code null} if not owned. When this method is called by a
585 * thread that is not the owner, the return value reflects a
586 * best-effort approximation of current lock status. For example,
587 * the owner may be momentarily {@code null} even if there are
588 * threads trying to acquire the lock but have not yet done so.
589 * This method is designed to facilitate construction of
590 * subclasses that provide more extensive lock monitoring
593 * @return the owner, or {@code null} if not owned
595 /*protected Thread getOwner() {
596 return sync.getOwner();
600 * Queries whether any threads are waiting to acquire this lock. Note that
601 * because cancellations may occur at any time, a {@code true}
602 * return does not guarantee that any other thread will ever
603 * acquire this lock. This method is designed primarily for use in
604 * monitoring of the system state.
606 * @return {@code true} if there may be other threads waiting to
609 /*public final boolean hasQueuedThreads() {
610 return sync.hasQueuedThreads();
615 * Queries whether the given thread is waiting to acquire this
616 * lock. Note that because cancellations may occur at any time, a
617 * {@code true} return does not guarantee that this thread
618 * will ever acquire this lock. This method is designed primarily for use
619 * in monitoring of the system state.
621 * @param thread the thread
622 * @return {@code true} if the given thread is queued waiting for this lock
623 * @throws NullPointerException if the thread is null
625 /*public final boolean hasQueuedThread(Thread thread) {
626 return sync.isQueued(thread);
631 * Returns an estimate of the number of threads waiting to
632 * acquire 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 of the system state, not for synchronization
638 * @return the estimated number of threads waiting for this lock
640 /*public final int getQueueLength() {
641 return sync.getQueueLength();
645 * Returns a collection containing threads that may be waiting to
646 * acquire this lock. Because the actual set of threads may change
647 * dynamically while constructing this result, the returned
648 * collection is only a best-effort estimate. The elements of the
649 * returned collection are in no particular order. This method is
650 * designed to facilitate construction of subclasses that provide
651 * more extensive monitoring facilities.
653 * @return the collection of threads
655 /*protected Collection<Thread> getQueuedThreads() {
656 return sync.getQueuedThreads();
660 * Queries whether any threads are waiting on the given condition
661 * associated with this lock. Note that because timeouts and
662 * interrupts may occur at any time, a {@code true} return does
663 * not guarantee that a future {@code signal} will awaken any
664 * threads. This method is designed primarily for use in
665 * monitoring of the system state.
667 * @param condition the condition
668 * @return {@code true} if there are any waiting threads
669 * @throws IllegalMonitorStateException if this lock is not held
670 * @throws IllegalArgumentException if the given condition is
671 * not associated with this lock
672 * @throws NullPointerException if the condition is null
674 /*public boolean hasWaiters(Condition condition) {
675 if (condition == null)
676 throw new NullPointerException();
677 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
678 throw new IllegalArgumentException("not owner");
679 return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
683 * Returns an estimate of the number of threads waiting on the
684 * given condition associated with this lock. Note that because
685 * timeouts and interrupts may occur at any time, the estimate
686 * serves only as an upper bound on the actual number of waiters.
687 * This method is designed for use in monitoring of the system
688 * state, not for synchronization control.
690 * @param condition the condition
691 * @return the estimated number of waiting threads
692 * @throws IllegalMonitorStateException if this lock is not held
693 * @throws IllegalArgumentException if the given condition is
694 * not associated with this lock
695 * @throws NullPointerException if the condition is null
697 /*public int getWaitQueueLength(Condition condition) {
698 if (condition == null)
699 throw new NullPointerException();
700 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
701 throw new IllegalArgumentException("not owner");
702 return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
706 * Returns a collection containing those threads that may be
707 * waiting on the given condition associated with this lock.
708 * Because the actual set of threads may change dynamically while
709 * constructing this result, the returned collection is only a
710 * best-effort estimate. The elements of the returned collection
711 * are in no particular order. This method is designed to
712 * facilitate construction of subclasses that provide more
713 * extensive condition monitoring facilities.
715 * @param condition the condition
716 * @return the collection of threads
717 * @throws IllegalMonitorStateException if this lock is not held
718 * @throws IllegalArgumentException if the given condition is
719 * not associated with this lock
720 * @throws NullPointerException if the condition is null
722 /*protected Collection<Thread> getWaitingThreads(Condition condition) {
723 if (condition == null)
724 throw new NullPointerException();
725 if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
726 throw new IllegalArgumentException("not owner");
727 return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
731 * Returns a string identifying this lock, as well as its lock state.
732 * The state, in brackets, includes either the String {@code "Unlocked"}
733 * or the String {@code "Locked by"} followed by the
734 * {@linkplain Thread#getName name} of the owning thread.
736 * @return a string identifying this lock, as well as its lock state
738 /*public String toString() {
739 Thread o = sync.getOwner();
740 return super.toString() + ((o == null) ?
742 "[Locked by thread " + o.getName() + "]");