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