KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > java > util > concurrent > locks > ReentrantLock


1 /*
2  * @(#)ReentrantLock.java 1.7 04/07/13
3  *
4  * Copyright 2004 Sun Microsystems, Inc. All rights reserved.
5  * SUN 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  * <tt>synchronized</tt> methods and statements, but with extended
17  * capabilities.
18  *
19  * <p> A <tt>ReentrantLock</tt> is <em>owned</em> by the thread last
20  * successfully locking, but not yet unlocking it. A thread invoking
21  * <tt>lock</tt> 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 <tt>true</tt>, 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 <tt>lock</tt> with a <tt>try</tt> 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 <tt>isLocked</tt> and
66  * <tt>getLockQueueLength</tt>, as well as some associated
67  * <tt>protected</tt> 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 2147483648 recursive locks by
75  * the same thread.
76  *
77  * @since 1.5
78  * @author Doug Lea
79  *
80  */

81 public class ReentrantLock implements Lock JavaDoc, java.io.Serializable JavaDoc {
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 JavaDoc {
92         /** Current owner thread */
93         transient Thread JavaDoc owner;
94
95         /**
96          * Perform {@link Lock#lock}. The main reason for subclassing
97          * is to allow fast path for nonfair version.
98          */

99         abstract void lock();
100
101         /**
102          * Perform non-fair tryLock. tryAcquire is
103          * implemented in subclasses, but both need nonfair
104          * try for trylock method
105          */

106         final boolean nonfairTryAcquire(int acquires) {
107             final Thread JavaDoc current = Thread.currentThread();
108             int c = getState();
109             if (c == 0) {
110                 if (compareAndSetState(0, acquires)) {
111                     owner = current;
112                     return true;
113                 }
114             }
115             else if (current == owner) {
116                 setState(c+acquires);
117                 return true;
118             }
119             return false;
120         }
121
122         protected final boolean tryRelease(int releases) {
123             int c = getState() - releases;
124             if (Thread.currentThread() != owner)
125                 throw new IllegalMonitorStateException JavaDoc();
126             boolean free = false;
127             if (c == 0) {
128                 free = true;
129                 owner = null;
130             }
131             setState(c);
132             return free;
133         }
134
135         protected final boolean isHeldExclusively() {
136             return getState() != 0 && owner == Thread.currentThread();
137         }
138
139         final ConditionObject newCondition() {
140             return new ConditionObject();
141         }
142
143         // Methods relayed from outer class
144

145         final Thread JavaDoc getOwner() {
146             int c = getState();
147             Thread JavaDoc o = owner;
148             return (c == 0)? null : o;
149         }
150         
151         final int getHoldCount() {
152             int c = getState();
153             Thread JavaDoc o = owner;
154             return (o == Thread.currentThread())? c : 0;
155         }
156         
157         final boolean isLocked() {
158             return getState() != 0;
159         }
160
161         /**
162          * Reconstitute this lock instance from a stream
163          * @param s the stream
164          */

165         private void readObject(java.io.ObjectInputStream JavaDoc s)
166             throws java.io.IOException JavaDoc, ClassNotFoundException JavaDoc {
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         /**
177          * Perform lock. Try immediate barge, backing up to normal
178          * acquire on failure.
179          */

180         final void lock() {
181             if (compareAndSetState(0, 1))
182                 owner = Thread.currentThread();
183             else
184                 acquire(1);
185         }
186
187         protected final boolean tryAcquire(int acquires) {
188             return nonfairTryAcquire(acquires);
189         }
190     }
191
192     /**
193      * Sync object for fair locks
194      */

195     final static class FairSync extends Sync {
196         final void lock() {
197             acquire(1);
198         }
199
200         /**
201          * Fair version of tryAcquire. Don't grant access unless
202          * recursive call or no waiters or is first.
203          */

204         protected final boolean tryAcquire(int acquires) {
205             final Thread JavaDoc current = Thread.currentThread();
206             int c = getState();
207             if (c == 0) {
208                 Thread JavaDoc first = getFirstQueuedThread();
209                 if ((first == null || first == current) &&
210                     compareAndSetState(0, acquires)) {
211                     owner = current;
212                     return true;
213                 }
214             }
215             else if (current == owner) {
216                 setState(c+acquires);
217                 return true;
218             }
219             return false;
220         }
221     }
222
223     /**
224      * Creates an instance of <tt>ReentrantLock</tt>.
225      * This is equivalent to using <tt>ReentrantLock(false)</tt>.
226      */

227     public ReentrantLock() {
228         sync = new NonfairSync();
229     }
230
231     /**
232      * Creates an instance of <tt>ReentrantLock</tt> with the
233      * given fairness policy.
234      * @param fair true if this lock will be fair; else false
235      */

236     public ReentrantLock(boolean fair) {
237         sync = (fair)? new FairSync() : new NonfairSync();
238     }
239
240     /**
241      * Acquires the lock.
242      *
243      * <p>Acquires the lock if it is not held by another thread and returns
244      * immediately, setting the lock hold count to one.
245      *
246      * <p>If the current thread
247      * already holds the lock then the hold count is incremented by one and
248      * 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      * {@link 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 {@link Thread#interrupt interrupts} the current
278      * 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 {@link 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 interruption
300      * point, preference is
301      * given to responding to the interrupt over normal or reentrant
302      * acquisition of the lock.
303      *
304      * @throws InterruptedException if the current thread is interrupted
305      */

306     public void lockInterruptibly() throws InterruptedException JavaDoc {
307         sync.acquireInterruptibly(1);
308     }
309
310     /**
311      * Acquires the lock only if it is not held by another thread at the time
312      * of invocation.
313      *
314      * <p>Acquires the lock if it is not held by another thread and
315      * returns immediately with the value <tt>true</tt>, setting the
316      * lock hold count to one. Even when this lock has been set to use a
317      * fair ordering policy, a call to <tt>tryLock()</tt> <em>will</em>
318      * immediately acquire the lock if it is available, whether or not
319      * other threads are currently waiting for the lock.
320      * This &quot;barging&quot; behavior can be useful in certain
321      * circumstances, even though it breaks fairness. If you want to honor
322      * the fairness setting for this lock, then use
323      * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
324      * which is almost equivalent (it also detects interruption).
325      *
326      * <p> If the current thread
327      * already holds this lock then the hold count is incremented by one and
328      * the method returns <tt>true</tt>.
329      *
330      * <p>If the lock is held by another thread then this method will return
331      * immediately with the value <tt>false</tt>.
332      *
333      * @return <tt>true</tt> if the lock was free and was acquired by the
334      * current thread, or the lock was already held by the current thread; and
335      * <tt>false</tt> otherwise.
336      */

337     public boolean tryLock() {
338         return sync.nonfairTryAcquire(1);
339     }
340
341     /**
342      * Acquires the lock if it is not held by another thread within the given
343      * waiting time and the current thread has not been
344      * {@link Thread#interrupt interrupted}.
345      *
346      * <p>Acquires the lock if it is not held by another thread and returns
347      * immediately with the value <tt>true</tt>, setting the lock hold count
348      * to one. If this lock has been set to use a fair ordering policy then
349      * an available lock <em>will not</em> be acquired if any other threads
350      * are waiting for the lock. This is in contrast to the {@link #tryLock()}
351      * method. If you want a timed <tt>tryLock</tt> that does permit barging on
352      * a fair lock then combine the timed and un-timed forms together:
353      *
354      * <pre>if (lock.tryLock() || lock.tryLock(timeout, unit) ) { ... }
355      * </pre>
356      *
357      * <p>If the current thread
358      * already holds this lock then the hold count is incremented by one and
359      * the method returns <tt>true</tt>.
360      *
361      * <p>If the lock is held by another thread then the
362      * current thread becomes disabled for thread scheduling
363      * purposes and lies dormant until one of three things happens:
364      *
365      * <ul>
366      *
367      * <li>The lock is acquired by the current thread; or
368      *
369      * <li>Some other thread {@link Thread#interrupt interrupts} the current
370      * thread; or
371      *
372      * <li>The specified waiting time elapses
373      *
374      * </ul>
375      *
376      * <p>If the lock is acquired then the value <tt>true</tt> is returned and
377      * the lock hold count is set to one.
378      *
379      * <p>If the current thread:
380      *
381      * <ul>
382      *
383      * <li>has its interrupted status set on entry to this method; or
384      *
385      * <li>is {@link Thread#interrupt interrupted} while acquiring
386      * the lock,
387      *
388      * </ul>
389      * then {@link InterruptedException} is thrown and the current thread's
390      * interrupted status is cleared.
391      *
392      * <p>If the specified waiting time elapses then the value <tt>false</tt>
393      * is returned.
394      * If the time is
395      * less than or equal to zero, the method will not wait at all.
396      *
397      * <p>In this implementation, as this method is an explicit interruption
398      * point, preference is
399      * given to responding to the interrupt over normal or reentrant
400      * acquisition of the lock, and over reporting the elapse of the waiting
401      * time.
402      *
403      * @param timeout the time to wait for the lock
404      * @param unit the time unit of the timeout argument
405      *
406      * @return <tt>true</tt> if the lock was free and was acquired by the
407      * current thread, or the lock was already held by the current thread; and
408      * <tt>false</tt> if the waiting time elapsed before the lock could be
409      * acquired.
410      *
411      * @throws InterruptedException if the current thread is interrupted
412      * @throws NullPointerException if unit is null
413      *
414      */

415     public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException JavaDoc {
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
423      * holder of this lock then the hold count is decremented. If the
424      * hold count is now zero then the lock is released. If the
425      * current thread is not the holder of this lock then {@link
426      * IllegalMonitorStateException} is thrown.
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      * {@link Condition#await() waiting} or {@link Condition#signal
448      * signalling} methods are called, then an {@link
449      * IllegalMonitorStateException} is thrown.
450      *
451      * <li>When the condition {@link 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 {@link Thread#interrupt interrupted} while
457      * 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 JavaDoc 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      * @return <tt>true</tt> if current thread holds this lock and
551      * <tt>false</tt> otherwise.
552      */

553     public boolean isHeldByCurrentThread() {
554         return sync.isHeldExclusively();
555     }
556
557     /**
558      * Queries if this lock is held by any thread. This method is
559      * designed for use in monitoring of the system state,
560      * not for synchronization control.
561      * @return <tt>true</tt> if any thread holds this lock and
562      * <tt>false</tt> otherwise.
563      */

564     public boolean isLocked() {
565         return sync.isLocked();
566     }
567
568     /**
569      * Returns true if this lock has fairness set true.
570      * @return true if this lock has fairness set true.
571      */

572     public final boolean isFair() {
573         return sync instanceof FairSync;
574     }
575
576     /**
577      * Returns the thread that currently owns this lock, or
578      * <tt>null</tt> if not owned. Note that the owner may be
579      * momentarily <tt>null</tt> even if there are threads trying to
580      * acquire the lock but have not yet done so. This method is
581      * designed to facilitate construction of subclasses that provide
582      * more extensive lock monitoring facilities.
583      * @return the owner, or <tt>null</tt> if not owned.
584      */

585     protected Thread JavaDoc getOwner() {
586         return sync.getOwner();
587     }
588
589     /**
590      * Queries whether any threads are waiting to acquire this lock. Note that
591      * because cancellations may occur at any time, a <tt>true</tt>
592      * return does not guarantee that any other thread will ever
593      * acquire this lock. This method is designed primarily for use in
594      * monitoring of the system state.
595      *
596      * @return true if there may be other threads waiting to acquire
597      * the lock.
598      */

599     public final boolean hasQueuedThreads() {
600         return sync.hasQueuedThreads();
601     }
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      * <tt>true</tt> 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 true if the given thread is queued waiting for this lock.
613      * @throws NullPointerException if thread is null
614      */

615     public final boolean hasQueuedThread(Thread JavaDoc thread) {
616         return sync.isQueued(thread);
617     }
618
619
620     /**
621      * Returns an estimate of the number of threads waiting to
622      * acquire this lock. The value is only an estimate because the number of
623      * threads may change dynamically while this method traverses
624      * internal data structures. This method is designed for use in
625      * monitoring of the system state, not for synchronization
626      * control.
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      * @return the collection of threads
642      */

643     protected Collection<Thread JavaDoc> getQueuedThreads() {
644         return sync.getQueuedThreads();
645     }
646
647     /**
648      * Queries whether any threads are waiting on the given condition
649      * associated with this lock. Note that because timeouts and
650      * interrupts may occur at any time, a <tt>true</tt> return does
651      * not guarantee that a future <tt>signal</tt> will awaken any
652      * threads. This method is designed primarily for use in
653      * monitoring of the system state.
654      * @param condition the condition
655      * @return <tt>true</tt> if there are any waiting threads.
656      * @throws IllegalMonitorStateException if this lock
657      * is not held
658      * @throws IllegalArgumentException if the given condition is
659      * not associated with this lock
660      * @throws NullPointerException if condition null
661      */

662     public boolean hasWaiters(Condition JavaDoc condition) {
663         if (condition == null)
664             throw new NullPointerException JavaDoc();
665         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject JavaDoc))
666             throw new IllegalArgumentException JavaDoc("not owner");
667         return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject JavaDoc)condition);
668     }
669
670     /**
671      * Returns an estimate of the number of threads waiting on the
672      * given condition associated with this lock. Note that because
673      * timeouts and interrupts may occur at any time, the estimate
674      * serves only as an upper bound on the actual number of waiters.
675      * This method is designed for use in monitoring of the system
676      * state, not for synchronization control.
677      * @param condition the condition
678      * @return the estimated number of waiting threads.
679      * @throws IllegalMonitorStateException if this lock
680      * is not held
681      * @throws IllegalArgumentException if the given condition is
682      * not associated with this lock
683      * @throws NullPointerException if condition null
684      */

685     public int getWaitQueueLength(Condition JavaDoc condition) {
686         if (condition == null)
687             throw new NullPointerException JavaDoc();
688         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject JavaDoc))
689             throw new IllegalArgumentException JavaDoc("not owner");
690         return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject JavaDoc)condition);
691     }
692
693     /**
694      * Returns a collection containing those threads that may be
695      * waiting on the given condition associated with this lock.
696      * Because the actual set of threads may change dynamically while
697      * constructing this result, the returned collection is only a
698      * best-effort estimate. The elements of the returned collection
699      * are in no particular order. This method is designed to
700      * facilitate construction of subclasses that provide more
701      * extensive condition monitoring facilities.
702      * @param condition the condition
703      * @return the collection of threads
704      * @throws IllegalMonitorStateException if this lock
705      * is not held
706      * @throws IllegalArgumentException if the given condition is
707      * not associated with this lock
708      * @throws NullPointerException if condition null
709      */

710     protected Collection<Thread JavaDoc> getWaitingThreads(Condition JavaDoc condition) {
711         if (condition == null)
712             throw new NullPointerException JavaDoc();
713         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject JavaDoc))
714             throw new IllegalArgumentException JavaDoc("not owner");
715         return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject JavaDoc)condition);
716     }
717
718     /**
719      * Returns a string identifying this lock, as well as its lock
720      * state. The state, in brackets, includes either the String
721      * &quot;Unlocked&quot; or the String &quot;Locked by&quot;
722      * followed by the {@link Thread#getName} of the owning thread.
723      * @return a string identifying this lock, as well as its lock state.
724      */

725     public String JavaDoc toString() {
726         Thread JavaDoc owner = sync.getOwner();
727         return super.toString() + ((owner == null) ?
728                                    "[Unlocked]" :
729                                    "[Locked by thread " + owner.getName() + "]");
730     }
731 }
732
Popular Tags