(锁) 系列篇

半世苍凉 提交于 2020-03-27 16:44:12

(锁) 系列篇

  

3.2、通过独占锁ReentrantLock理解AQS
 
目录
 
 
 
 
ReentrantLock和AQS源码(以open-jdk 1.8.0为源码分析版本)
 
 
 
  1 /*
  2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  3  *
  4  * This code is free software; you can redistribute it and/or modify it
  5  * under the terms of the GNU General Public License version 2 only, as
  6  * published by the Free Software Foundation.  Oracle designates this
  7  * particular file as subject to the "Classpath" exception as provided
  8  * by Oracle in the LICENSE file that accompanied this code.
  9  *
 10  * This code is distributed in the hope that it will be useful, but WITHOUT
 11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 13  * version 2 for more details (a copy is included in the LICENSE file that
 14  * accompanied this code).
 15  *
 16  * You should have received a copy of the GNU General Public License version
 17  * 2 along with this work; if not, write to the Free Software Foundation,
 18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 19  *
 20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 21  * or visit www.oracle.com if you need additional information or have any
 22  * questions.
 23  */
 24 
 25 /*
 26  * This file is available under and governed by the GNU General Public
 27  * License version 2 only, as published by the Free Software Foundation.
 28  * However, the following notice accompanied the original version of this
 29  * file:
 30  *
 31  * Written by Doug Lea with assistance from members of JCP JSR-166
 32  * Expert Group and released to the public domain, as explained at
 33  * http://creativecommons.org/publicdomain/zero/1.0/
 34  */
 35 
 36 package java.util.concurrent.locks;
 37 import java.util.concurrent.TimeUnit;
 38 import java.util.Collection;
 39 
 40 /**
 41  * A reentrant mutual exclusion {@link Lock} with the same basic
 42  * behavior and semantics as the implicit monitor lock accessed using
 43  * {@code synchronized} methods and statements, but with extended
 44  * capabilities.
 45  *
 46  * <p>A {@code ReentrantLock} is <em>owned</em> by the thread last
 47  * successfully locking, but not yet unlocking it. A thread invoking
 48  * {@code lock} will return, successfully acquiring the lock, when
 49  * the lock is not owned by another thread. The method will return
 50  * immediately if the current thread already owns the lock. This can
 51  * be checked using methods {@link #isHeldByCurrentThread}, and {@link
 52  * #getHoldCount}.
 53  *
 54  * <p>The constructor for this class accepts an optional
 55  * <em>fairness</em> parameter.  When set {@code true}, under
 56  * contention, locks favor granting access to the longest-waiting
 57  * thread.  Otherwise this lock does not guarantee any particular
 58  * access order.  Programs using fair locks accessed by many threads
 59  * may display lower overall throughput (i.e., are slower; often much
 60  * slower) than those using the default setting, but have smaller
 61  * variances in times to obtain locks and guarantee lack of
 62  * starvation. Note however, that fairness of locks does not guarantee
 63  * fairness of thread scheduling. Thus, one of many threads using a
 64  * fair lock may obtain it multiple times in succession while other
 65  * active threads are not progressing and not currently holding the
 66  * lock.
 67  * Also note that the untimed {@link #tryLock()} method does not
 68  * honor the fairness setting. It will succeed if the lock
 69  * is available even if other threads are waiting.
 70  *
 71  * <p>It is recommended practice to <em>always</em> immediately
 72  * follow a call to {@code lock} with a {@code try} block, most
 73  * typically in a before/after construction such as:
 74  *
 75  *  <pre> {@code
 76  * class X {
 77  *   private final ReentrantLock lock = new ReentrantLock();
 78  *   // ...
 79  *
 80  *   public void m() {
 81  *     lock.lock();  // block until condition holds
 82  *     try {
 83  *       // ... method body
 84  *     } finally {
 85  *       lock.unlock()
 86  *     }
 87  *   }
 88  * }}</pre>
 89  *
 90  * <p>In addition to implementing the {@link Lock} interface, this
 91  * class defines a number of {@code public} and {@code protected}
 92  * methods for inspecting the state of the lock.  Some of these
 93  * methods are only useful for instrumentation and monitoring.
 94  *
 95  * <p>Serialization of this class behaves in the same way as built-in
 96  * locks: a deserialized lock is in the unlocked state, regardless of
 97  * its state when serialized.
 98  *
 99  * <p>This lock supports a maximum of 2147483647 recursive locks by
100  * the same thread. Attempts to exceed this limit result in
101  * {@link Error} throws from locking methods.
102  *
103  * @since 1.5
104  * @author Doug Lea
105  */
106 public class ReentrantLock implements Lock, java.io.Serializable {
107     private static final long serialVersionUID = 7373984872572414699L;
108     /** Synchronizer providing all implementation mechanics */
109     private final Sync sync;
110 
111     /**
112      * Base of synchronization control for this lock. Subclassed
113      * into fair and nonfair versions below. Uses AQS state to
114      * represent the number of holds on the lock.
115      */
116     abstract static class Sync extends AbstractQueuedSynchronizer {
117         private static final long serialVersionUID = -5179523762034025860L;
118 
119         /**
120          * Performs {@link Lock#lock}. The main reason for subclassing
121          * is to allow fast path for nonfair version.
122          */
123         abstract void lock();
124 
125         /**
126          * Performs non-fair tryLock.  tryAcquire is implemented in
127          * subclasses, but both need nonfair try for trylock method.
128          */
129         final boolean nonfairTryAcquire(int acquires) {
130             final Thread current = Thread.currentThread();
131             int c = getState();
132             if (c == 0) {
133                 if (compareAndSetState(0, acquires)) {
134                     setExclusiveOwnerThread(current);
135                     return true;
136                 }
137             }
138             else if (current == getExclusiveOwnerThread()) {
139                 int nextc = c + acquires;
140                 if (nextc < 0) // overflow
141                     throw new Error("Maximum lock count exceeded");
142                 setState(nextc);
143                 return true;
144             }
145             return false;
146         }
147 
148         protected final boolean tryRelease(int releases) {
149             int c = getState() - releases;
150             if (Thread.currentThread() != getExclusiveOwnerThread())
151                 throw new IllegalMonitorStateException();
152             boolean free = false;
153             if (c == 0) {
154                 free = true;
155                 setExclusiveOwnerThread(null);
156             }
157             setState(c);
158             return free;
159         }
160 
161         protected final boolean isHeldExclusively() {
162             // While we must in general read state before owner,
163             // we don't need to do so to check if current thread is owner
164             return getExclusiveOwnerThread() == Thread.currentThread();
165         }
166 
167         final ConditionObject newCondition() {
168             return new ConditionObject();
169         }
170 
171         // Methods relayed from outer class
172 
173         final Thread getOwner() {
174             return getState() == 0 ? null : getExclusiveOwnerThread();
175         }
176 
177         final int getHoldCount() {
178             return isHeldExclusively() ? getState() : 0;
179         }
180 
181         final boolean isLocked() {
182             return getState() != 0;
183         }
184 
185         /**
186          * Reconstitutes the instance from a stream (that is, deserializes it).
187          */
188         private void readObject(java.io.ObjectInputStream s)
189             throws java.io.IOException, ClassNotFoundException {
190             s.defaultReadObject();
191             setState(0); // reset to unlocked state
192         }
193     }
194 
195     /**
196      * Sync object for non-fair locks
197      */
198     static final class NonfairSync extends Sync {
199         private static final long serialVersionUID = 7316153563782823691L;
200 
201         /**
202          * Performs lock.  Try immediate barge, backing up to normal
203          * acquire on failure.
204          */
205         final void lock() {
206             if (compareAndSetState(0, 1))
207                 setExclusiveOwnerThread(Thread.currentThread());
208             else
209                 acquire(1);
210         }
211 
212         protected final boolean tryAcquire(int acquires) {
213             return nonfairTryAcquire(acquires);
214         }
215     }
216 
217     /**
218      * Sync object for fair locks
219      */
220     static final class FairSync extends Sync {
221         private static final long serialVersionUID = -3000897897090466540L;
222 
223         final void lock() {
224             acquire(1);
225         }
226 
227         /**
228          * Fair version of tryAcquire.  Don't grant access unless
229          * recursive call or no waiters or is first.
230          */
231         protected final boolean tryAcquire(int acquires) {
232             final Thread current = Thread.currentThread();
233             int c = getState();
234             if (c == 0) {
235                 if (!hasQueuedPredecessors() &&
236                     compareAndSetState(0, acquires)) {
237                     setExclusiveOwnerThread(current);
238                     return true;
239                 }
240             }
241             else if (current == getExclusiveOwnerThread()) {
242                 int nextc = c + acquires;
243                 if (nextc < 0)
244                     throw new Error("Maximum lock count exceeded");
245                 setState(nextc);
246                 return true;
247             }
248             return false;
249         }
250     }
251 
252     /**
253      * Creates an instance of {@code ReentrantLock}.
254      * This is equivalent to using {@code ReentrantLock(false)}.
255      */
256     public ReentrantLock() {
257         sync = new NonfairSync();
258     }
259 
260     /**
261      * Creates an instance of {@code ReentrantLock} with the
262      * given fairness policy.
263      *
264      * @param fair {@code true} if this lock should use a fair ordering policy
265      */
266     public ReentrantLock(boolean fair) {
267         sync = fair ? new FairSync() : new NonfairSync();
268     }
269 
270     /**
271      * Acquires the lock.
272      *
273      * <p>Acquires the lock if it is not held by another thread and returns
274      * immediately, setting the lock hold count to one.
275      *
276      * <p>If the current thread already holds the lock then the hold
277      * count is incremented by one and the method returns immediately.
278      *
279      * <p>If the lock is held by another thread then the
280      * current thread becomes disabled for thread scheduling
281      * purposes and lies dormant until the lock has been acquired,
282      * at which time the lock hold count is set to one.
283      */
284     public void lock() {
285         sync.lock();
286     }
287 
288     /**
289      * Acquires the lock unless the current thread is
290      * {@linkplain Thread#interrupt interrupted}.
291      *
292      * <p>Acquires the lock if it is not held by another thread and returns
293      * immediately, setting the lock hold count to one.
294      *
295      * <p>If the current thread already holds this lock then the hold count
296      * is incremented by one and the method returns immediately.
297      *
298      * <p>If the lock is held by another thread then the
299      * current thread becomes disabled for thread scheduling
300      * purposes and lies dormant until one of two things happens:
301      *
302      * <ul>
303      *
304      * <li>The lock is acquired by the current thread; or
305      *
306      * <li>Some other thread {@linkplain Thread#interrupt interrupts} the
307      * current thread.
308      *
309      * </ul>
310      *
311      * <p>If the lock is acquired by the current thread then the lock hold
312      * count is set to one.
313      *
314      * <p>If the current thread:
315      *
316      * <ul>
317      *
318      * <li>has its interrupted status set on entry to this method; or
319      *
320      * <li>is {@linkplain Thread#interrupt interrupted} while acquiring
321      * the lock,
322      *
323      * </ul>
324      *
325      * then {@link InterruptedException} is thrown and the current thread's
326      * interrupted status is cleared.
327      *
328      * <p>In this implementation, as this method is an explicit
329      * interruption point, preference is given to responding to the
330      * interrupt over normal or reentrant acquisition of the lock.
331      *
332      * @throws InterruptedException if the current thread is interrupted
333      */
334     public void lockInterruptibly() throws InterruptedException {
335         sync.acquireInterruptibly(1);
336     }
337 
338     /**
339      * Acquires the lock only if it is not held by another thread at the time
340      * of invocation.
341      *
342      * <p>Acquires the lock if it is not held by another thread and
343      * returns immediately with the value {@code true}, setting the
344      * lock hold count to one. Even when this lock has been set to use a
345      * fair ordering policy, a call to {@code tryLock()} <em>will</em>
346      * immediately acquire the lock if it is available, whether or not
347      * other threads are currently waiting for the lock.
348      * This &quot;barging&quot; behavior can be useful in certain
349      * circumstances, even though it breaks fairness. If you want to honor
350      * the fairness setting for this lock, then use
351      * {@link #tryLock(long, TimeUnit) tryLock(0, TimeUnit.SECONDS) }
352      * which is almost equivalent (it also detects interruption).
353      *
354      * <p>If the current thread already holds this lock then the hold
355      * count is incremented by one and the method returns {@code true}.
356      *
357      * <p>If the lock is held by another thread then this method will return
358      * immediately with the value {@code false}.
359      *
360      * @return {@code true} if the lock was free and was acquired by the
361      *         current thread, or the lock was already held by the current
362      *         thread; and {@code false} otherwise
363      */
364     public boolean tryLock() {
365         return sync.nonfairTryAcquire(1);
366     }
367 
368     /**
369      * Acquires the lock if it is not held by another thread within the given
370      * waiting time and the current thread has not been
371      * {@linkplain Thread#interrupt interrupted}.
372      *
373      * <p>Acquires the lock if it is not held by another thread and returns
374      * immediately with the value {@code true}, setting the lock hold count
375      * to one. If this lock has been set to use a fair ordering policy then
376      * an available lock <em>will not</em> be acquired if any other threads
377      * are waiting for the lock. This is in contrast to the {@link #tryLock()}
378      * method. If you want a timed {@code tryLock} that does permit barging on
379      * a fair lock then combine the timed and un-timed forms together:
380      *
381      *  <pre> {@code
382      * if (lock.tryLock() ||
383      *     lock.tryLock(timeout, unit)) {
384      *   ...
385      * }}</pre>
386      *
387      * <p>If the current thread
388      * already holds this lock then the hold count is incremented by one and
389      * the method returns {@code true}.
390      *
391      * <p>If the lock is held by another thread then the
392      * current thread becomes disabled for thread scheduling
393      * purposes and lies dormant until one of three things happens:
394      *
395      * <ul>
396      *
397      * <li>The lock is acquired by the current thread; or
398      *
399      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
400      * the current thread; or
401      *
402      * <li>The specified waiting time elapses
403      *
404      * </ul>
405      *
406      * <p>If the lock is acquired then the value {@code true} is returned and
407      * the lock hold count is set to one.
408      *
409      * <p>If the current thread:
410      *
411      * <ul>
412      *
413      * <li>has its interrupted status set on entry to this method; or
414      *
415      * <li>is {@linkplain Thread#interrupt interrupted} while
416      * acquiring the lock,
417      *
418      * </ul>
419      * then {@link InterruptedException} is thrown and the current thread's
420      * interrupted status is cleared.
421      *
422      * <p>If the specified waiting time elapses then the value {@code false}
423      * is returned.  If the time is less than or equal to zero, the method
424      * will not wait at all.
425      *
426      * <p>In this implementation, as this method is an explicit
427      * interruption point, preference is given to responding to the
428      * interrupt over normal or reentrant acquisition of the lock, and
429      * over reporting the elapse of the waiting time.
430      *
431      * @param timeout the time to wait for the lock
432      * @param unit the time unit of the timeout argument
433      * @return {@code true} if the lock was free and was acquired by the
434      *         current thread, or the lock was already held by the current
435      *         thread; and {@code false} if the waiting time elapsed before
436      *         the lock could be acquired
437      * @throws InterruptedException if the current thread is interrupted
438      * @throws NullPointerException if the time unit is null
439      */
440     public boolean tryLock(long timeout, TimeUnit unit)
441             throws InterruptedException {
442         return sync.tryAcquireNanos(1, unit.toNanos(timeout));
443     }
444 
445     /**
446      * Attempts to release this lock.
447      *
448      * <p>If the current thread is the holder of this lock then the hold
449      * count is decremented.  If the hold count is now zero then the lock
450      * is released.  If the current thread is not the holder of this
451      * lock then {@link IllegalMonitorStateException} is thrown.
452      *
453      * @throws IllegalMonitorStateException if the current thread does not
454      *         hold this lock
455      */
456     public void unlock() {
457         sync.release(1);
458     }
459 
460     /**
461      * Returns a {@link Condition} instance for use with this
462      * {@link Lock} instance.
463      *
464      * <p>The returned {@link Condition} instance supports the same
465      * usages as do the {@link Object} monitor methods ({@link
466      * Object#wait() wait}, {@link Object#notify notify}, and {@link
467      * Object#notifyAll notifyAll}) when used with the built-in
468      * monitor lock.
469      *
470      * <ul>
471      *
472      * <li>If this lock is not held when any of the {@link Condition}
473      * {@linkplain Condition#await() waiting} or {@linkplain
474      * Condition#signal signalling} methods are called, then an {@link
475      * IllegalMonitorStateException} is thrown.
476      *
477      * <li>When the condition {@linkplain Condition#await() waiting}
478      * methods are called the lock is released and, before they
479      * return, the lock is reacquired and the lock hold count restored
480      * to what it was when the method was called.
481      *
482      * <li>If a thread is {@linkplain Thread#interrupt interrupted}
483      * while waiting then the wait will terminate, an {@link
484      * InterruptedException} will be thrown, and the thread's
485      * interrupted status will be cleared.
486      *
487      * <li> Waiting threads are signalled in FIFO order.
488      *
489      * <li>The ordering of lock reacquisition for threads returning
490      * from waiting methods is the same as for threads initially
491      * acquiring the lock, which is in the default case not specified,
492      * but for <em>fair</em> locks favors those threads that have been
493      * waiting the longest.
494      *
495      * </ul>
496      *
497      * @return the Condition object
498      */
499     public Condition newCondition() {
500         return sync.newCondition();
501     }
502 
503     /**
504      * Queries the number of holds on this lock by the current thread.
505      *
506      * <p>A thread has a hold on a lock for each lock action that is not
507      * matched by an unlock action.
508      *
509      * <p>The hold count information is typically only used for testing and
510      * debugging purposes. For example, if a certain section of code should
511      * not be entered with the lock already held then we can assert that
512      * fact:
513      *
514      *  <pre> {@code
515      * class X {
516      *   ReentrantLock lock = new ReentrantLock();
517      *   // ...
518      *   public void m() {
519      *     assert lock.getHoldCount() == 0;
520      *     lock.lock();
521      *     try {
522      *       // ... method body
523      *     } finally {
524      *       lock.unlock();
525      *     }
526      *   }
527      * }}</pre>
528      *
529      * @return the number of holds on this lock by the current thread,
530      *         or zero if this lock is not held by the current thread
531      */
532     public int getHoldCount() {
533         return sync.getHoldCount();
534     }
535 
536     /**
537      * Queries if this lock is held by the current thread.
538      *
539      * <p>Analogous to the {@link Thread#holdsLock(Object)} method for
540      * built-in monitor locks, this method is typically used for
541      * debugging and testing. For example, a method that should only be
542      * called while a lock is held can assert that this is the case:
543      *
544      *  <pre> {@code
545      * class X {
546      *   ReentrantLock lock = new ReentrantLock();
547      *   // ...
548      *
549      *   public void m() {
550      *       assert lock.isHeldByCurrentThread();
551      *       // ... method body
552      *   }
553      * }}</pre>
554      *
555      * <p>It can also be used to ensure that a reentrant lock is used
556      * in a non-reentrant manner, for example:
557      *
558      *  <pre> {@code
559      * class X {
560      *   ReentrantLock lock = new ReentrantLock();
561      *   // ...
562      *
563      *   public void m() {
564      *       assert !lock.isHeldByCurrentThread();
565      *       lock.lock();
566      *       try {
567      *           // ... method body
568      *       } finally {
569      *           lock.unlock();
570      *       }
571      *   }
572      * }}</pre>
573      *
574      * @return {@code true} if current thread holds this lock and
575      *         {@code false} otherwise
576      */
577     public boolean isHeldByCurrentThread() {
578         return sync.isHeldExclusively();
579     }
580 
581     /**
582      * Queries if this lock is held by any thread. This method is
583      * designed for use in monitoring of the system state,
584      * not for synchronization control.
585      *
586      * @return {@code true} if any thread holds this lock and
587      *         {@code false} otherwise
588      */
589     public boolean isLocked() {
590         return sync.isLocked();
591     }
592 
593     /**
594      * Returns {@code true} if this lock has fairness set true.
595      *
596      * @return {@code true} if this lock has fairness set true
597      */
598     public final boolean isFair() {
599         return sync instanceof FairSync;
600     }
601 
602     /**
603      * Returns the thread that currently owns this lock, or
604      * {@code null} if not owned. When this method is called by a
605      * thread that is not the owner, the return value reflects a
606      * best-effort approximation of current lock status. For example,
607      * the owner may be momentarily {@code null} even if there are
608      * threads trying to acquire the lock but have not yet done so.
609      * This method is designed to facilitate construction of
610      * subclasses that provide more extensive lock monitoring
611      * facilities.
612      *
613      * @return the owner, or {@code null} if not owned
614      */
615     protected Thread getOwner() {
616         return sync.getOwner();
617     }
618 
619     /**
620      * Queries whether any threads are waiting to acquire this lock. Note that
621      * because cancellations may occur at any time, a {@code true}
622      * return does not guarantee that any other thread will ever
623      * acquire this lock.  This method is designed primarily for use in
624      * monitoring of the system state.
625      *
626      * @return {@code true} if there may be other threads waiting to
627      *         acquire the lock
628      */
629     public final boolean hasQueuedThreads() {
630         return sync.hasQueuedThreads();
631     }
632 
633     /**
634      * Queries whether the given thread is waiting to acquire this
635      * lock. Note that because cancellations may occur at any time, a
636      * {@code true} return does not guarantee that this thread
637      * will ever acquire this lock.  This method is designed primarily for use
638      * in monitoring of the system state.
639      *
640      * @param thread the thread
641      * @return {@code true} if the given thread is queued waiting for this lock
642      * @throws NullPointerException if the thread is null
643      */
644     public final boolean hasQueuedThread(Thread thread) {
645         return sync.isQueued(thread);
646     }
647 
648     /**
649      * Returns an estimate of the number of threads waiting to
650      * acquire this lock.  The value is only an estimate because the number of
651      * threads may change dynamically while this method traverses
652      * internal data structures.  This method is designed for use in
653      * monitoring of the system state, not for synchronization
654      * control.
655      *
656      * @return the estimated number of threads waiting for this lock
657      */
658     public final int getQueueLength() {
659         return sync.getQueueLength();
660     }
661 
662     /**
663      * Returns a collection containing threads that may be waiting to
664      * acquire this lock.  Because the actual set of threads may change
665      * dynamically while constructing this result, the returned
666      * collection is only a best-effort estimate.  The elements of the
667      * returned collection are in no particular order.  This method is
668      * designed to facilitate construction of subclasses that provide
669      * more extensive monitoring facilities.
670      *
671      * @return the collection of threads
672      */
673     protected Collection<Thread> getQueuedThreads() {
674         return sync.getQueuedThreads();
675     }
676 
677     /**
678      * Queries whether any threads are waiting on the given condition
679      * associated with this lock. Note that because timeouts and
680      * interrupts may occur at any time, a {@code true} return does
681      * not guarantee that a future {@code signal} will awaken any
682      * threads.  This method is designed primarily for use in
683      * monitoring of the system state.
684      *
685      * @param condition the condition
686      * @return {@code true} if there are any waiting threads
687      * @throws IllegalMonitorStateException if this lock is not held
688      * @throws IllegalArgumentException if the given condition is
689      *         not associated with this lock
690      * @throws NullPointerException if the condition is null
691      */
692     public boolean hasWaiters(Condition condition) {
693         if (condition == null)
694             throw new NullPointerException();
695         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
696             throw new IllegalArgumentException("not owner");
697         return sync.hasWaiters((AbstractQueuedSynchronizer.ConditionObject)condition);
698     }
699 
700     /**
701      * Returns an estimate of the number of threads waiting on the
702      * given condition associated with this lock. Note that because
703      * timeouts and interrupts may occur at any time, the estimate
704      * serves only as an upper bound on the actual number of waiters.
705      * This method is designed for use in monitoring of the system
706      * state, not for synchronization control.
707      *
708      * @param condition the condition
709      * @return the estimated number of waiting threads
710      * @throws IllegalMonitorStateException if this lock is not held
711      * @throws IllegalArgumentException if the given condition is
712      *         not associated with this lock
713      * @throws NullPointerException if the condition is null
714      */
715     public int getWaitQueueLength(Condition condition) {
716         if (condition == null)
717             throw new NullPointerException();
718         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
719             throw new IllegalArgumentException("not owner");
720         return sync.getWaitQueueLength((AbstractQueuedSynchronizer.ConditionObject)condition);
721     }
722 
723     /**
724      * Returns a collection containing those threads that may be
725      * waiting on the given condition associated with this lock.
726      * Because the actual set of threads may change dynamically while
727      * constructing this result, the returned collection is only a
728      * best-effort estimate. The elements of the returned collection
729      * are in no particular order.  This method is designed to
730      * facilitate construction of subclasses that provide more
731      * extensive condition monitoring facilities.
732      *
733      * @param condition the condition
734      * @return the collection of threads
735      * @throws IllegalMonitorStateException if this lock is not held
736      * @throws IllegalArgumentException if the given condition is
737      *         not associated with this lock
738      * @throws NullPointerException if the condition is null
739      */
740     protected Collection<Thread> getWaitingThreads(Condition condition) {
741         if (condition == null)
742             throw new NullPointerException();
743         if (!(condition instanceof AbstractQueuedSynchronizer.ConditionObject))
744             throw new IllegalArgumentException("not owner");
745         return sync.getWaitingThreads((AbstractQueuedSynchronizer.ConditionObject)condition);
746     }
747 
748     /**
749      * Returns a string identifying this lock, as well as its lock state.
750      * The state, in brackets, includes either the String {@code "Unlocked"}
751      * or the String {@code "Locked by"} followed by the
752      * {@linkplain Thread#getName name} of the owning thread.
753      *
754      * @return a string identifying this lock, as well as its lock state
755      */
756     public String toString() {
757         Thread o = sync.getOwner();
758         return super.toString() + ((o == null) ?
759                                    "[Unlocked]" :
760                                    "[Locked by thread " + o.getName() + "]");
761     }
762 }
ReentrantLock.java
   1 /*
   2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   3  *
   4  * This code is free software; you can redistribute it and/or modify it
   5  * under the terms of the GNU General Public License version 2 only, as
   6  * published by the Free Software Foundation.  Oracle designates this
   7  * particular file as subject to the "Classpath" exception as provided
   8  * by Oracle in the LICENSE file that accompanied this code.
   9  *
  10  * This code is distributed in the hope that it will be useful, but WITHOUT
  11  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  12  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  13  * version 2 for more details (a copy is included in the LICENSE file that
  14  * accompanied this code).
  15  *
  16  * You should have received a copy of the GNU General Public License version
  17  * 2 along with this work; if not, write to the Free Software Foundation,
  18  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  19  *
  20  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  21  * or visit www.oracle.com if you need additional information or have any
  22  * questions.
  23  */
  24 
  25 /*
  26  * This file is available under and governed by the GNU General Public
  27  * License version 2 only, as published by the Free Software Foundation.
  28  * However, the following notice accompanied the original version of this
  29  * file:
  30  *
  31  * Written by Doug Lea with assistance from members of JCP JSR-166
  32  * Expert Group and released to the public domain, as explained at
  33  * http://creativecommons.org/publicdomain/zero/1.0/
  34  */
  35 
  36 package java.util.concurrent.locks;
  37 import java.util.concurrent.TimeUnit;
  38 import java.util.ArrayList;
  39 import java.util.Collection;
  40 import java.util.Date;
  41 import sun.misc.Unsafe;
  42 
  43 /**
  44  * Provides a framework for implementing blocking locks and related
  45  * synchronizers (semaphores, events, etc) that rely on
  46  * first-in-first-out (FIFO) wait queues.  This class is designed to
  47  * be a useful basis for most kinds of synchronizers that rely on a
  48  * single atomic {@code int} value to represent state. Subclasses
  49  * must define the protected methods that change this state, and which
  50  * define what that state means in terms of this object being acquired
  51  * or released.  Given these, the other methods in this class carry
  52  * out all queuing and blocking mechanics. Subclasses can maintain
  53  * other state fields, but only the atomically updated {@code int}
  54  * value manipulated using methods {@link #getState}, {@link
  55  * #setState} and {@link #compareAndSetState} is tracked with respect
  56  * to synchronization.
  57  *
  58  * <p>Subclasses should be defined as non-public internal helper
  59  * classes that are used to implement the synchronization properties
  60  * of their enclosing class.  Class
  61  * {@code AbstractQueuedSynchronizer} does not implement any
  62  * synchronization interface.  Instead it defines methods such as
  63  * {@link #acquireInterruptibly} that can be invoked as
  64  * appropriate by concrete locks and related synchronizers to
  65  * implement their public methods.
  66  *
  67  * <p>This class supports either or both a default <em>exclusive</em>
  68  * mode and a <em>shared</em> mode. When acquired in exclusive mode,
  69  * attempted acquires by other threads cannot succeed. Shared mode
  70  * acquires by multiple threads may (but need not) succeed. This class
  71  * does not &quot;understand&quot; these differences except in the
  72  * mechanical sense that when a shared mode acquire succeeds, the next
  73  * waiting thread (if one exists) must also determine whether it can
  74  * acquire as well. Threads waiting in the different modes share the
  75  * same FIFO queue. Usually, implementation subclasses support only
  76  * one of these modes, but both can come into play for example in a
  77  * {@link ReadWriteLock}. Subclasses that support only exclusive or
  78  * only shared modes need not define the methods supporting the unused mode.
  79  *
  80  * <p>This class defines a nested {@link ConditionObject} class that
  81  * can be used as a {@link Condition} implementation by subclasses
  82  * supporting exclusive mode for which method {@link
  83  * #isHeldExclusively} reports whether synchronization is exclusively
  84  * held with respect to the current thread, method {@link #release}
  85  * invoked with the current {@link #getState} value fully releases
  86  * this object, and {@link #acquire}, given this saved state value,
  87  * eventually restores this object to its previous acquired state.  No
  88  * {@code AbstractQueuedSynchronizer} method otherwise creates such a
  89  * condition, so if this constraint cannot be met, do not use it.  The
  90  * behavior of {@link ConditionObject} depends of course on the
  91  * semantics of its synchronizer implementation.
  92  *
  93  * <p>This class provides inspection, instrumentation, and monitoring
  94  * methods for the internal queue, as well as similar methods for
  95  * condition objects. These can be exported as desired into classes
  96  * using an {@code AbstractQueuedSynchronizer} for their
  97  * synchronization mechanics.
  98  *
  99  * <p>Serialization of this class stores only the underlying atomic
 100  * integer maintaining state, so deserialized objects have empty
 101  * thread queues. Typical subclasses requiring serializability will
 102  * define a {@code readObject} method that restores this to a known
 103  * initial state upon deserialization.
 104  *
 105  * <h3>Usage</h3>
 106  *
 107  * <p>To use this class as the basis of a synchronizer, redefine the
 108  * following methods, as applicable, by inspecting and/or modifying
 109  * the synchronization state using {@link #getState}, {@link
 110  * #setState} and/or {@link #compareAndSetState}:
 111  *
 112  * <ul>
 113  * <li> {@link #tryAcquire}
 114  * <li> {@link #tryRelease}
 115  * <li> {@link #tryAcquireShared}
 116  * <li> {@link #tryReleaseShared}
 117  * <li> {@link #isHeldExclusively}
 118  * </ul>
 119  *
 120  * Each of these methods by default throws {@link
 121  * UnsupportedOperationException}.  Implementations of these methods
 122  * must be internally thread-safe, and should in general be short and
 123  * not block. Defining these methods is the <em>only</em> supported
 124  * means of using this class. All other methods are declared
 125  * {@code final} because they cannot be independently varied.
 126  *
 127  * <p>You may also find the inherited methods from {@link
 128  * AbstractOwnableSynchronizer} useful to keep track of the thread
 129  * owning an exclusive synchronizer.  You are encouraged to use them
 130  * -- this enables monitoring and diagnostic tools to assist users in
 131  * determining which threads hold locks.
 132  *
 133  * <p>Even though this class is based on an internal FIFO queue, it
 134  * does not automatically enforce FIFO acquisition policies.  The core
 135  * of exclusive synchronization takes the form:
 136  *
 137  * <pre>
 138  * Acquire:
 139  *     while (!tryAcquire(arg)) {
 140  *        <em>enqueue thread if it is not already queued</em>;
 141  *        <em>possibly block current thread</em>;
 142  *     }
 143  *
 144  * Release:
 145  *     if (tryRelease(arg))
 146  *        <em>unblock the first queued thread</em>;
 147  * </pre>
 148  *
 149  * (Shared mode is similar but may involve cascading signals.)
 150  *
 151  * <p id="barging">Because checks in acquire are invoked before
 152  * enqueuing, a newly acquiring thread may <em>barge</em> ahead of
 153  * others that are blocked and queued.  However, you can, if desired,
 154  * define {@code tryAcquire} and/or {@code tryAcquireShared} to
 155  * disable barging by internally invoking one or more of the inspection
 156  * methods, thereby providing a <em>fair</em> FIFO acquisition order.
 157  * In particular, most fair synchronizers can define {@code tryAcquire}
 158  * to return {@code false} if {@link #hasQueuedPredecessors} (a method
 159  * specifically designed to be used by fair synchronizers) returns
 160  * {@code true}.  Other variations are possible.
 161  *
 162  * <p>Throughput and scalability are generally highest for the
 163  * default barging (also known as <em>greedy</em>,
 164  * <em>renouncement</em>, and <em>convoy-avoidance</em>) strategy.
 165  * While this is not guaranteed to be fair or starvation-free, earlier
 166  * queued threads are allowed to recontend before later queued
 167  * threads, and each recontention has an unbiased chance to succeed
 168  * against incoming threads.  Also, while acquires do not
 169  * &quot;spin&quot; in the usual sense, they may perform multiple
 170  * invocations of {@code tryAcquire} interspersed with other
 171  * computations before blocking.  This gives most of the benefits of
 172  * spins when exclusive synchronization is only briefly held, without
 173  * most of the liabilities when it isn't. If so desired, you can
 174  * augment this by preceding calls to acquire methods with
 175  * "fast-path" checks, possibly prechecking {@link #hasContended}
 176  * and/or {@link #hasQueuedThreads} to only do so if the synchronizer
 177  * is likely not to be contended.
 178  *
 179  * <p>This class provides an efficient and scalable basis for
 180  * synchronization in part by specializing its range of use to
 181  * synchronizers that can rely on {@code int} state, acquire, and
 182  * release parameters, and an internal FIFO wait queue. When this does
 183  * not suffice, you can build synchronizers from a lower level using
 184  * {@link java.util.concurrent.atomic atomic} classes, your own custom
 185  * {@link java.util.Queue} classes, and {@link LockSupport} blocking
 186  * support.
 187  *
 188  * <h3>Usage Examples</h3>
 189  *
 190  * <p>Here is a non-reentrant mutual exclusion lock class that uses
 191  * the value zero to represent the unlocked state, and one to
 192  * represent the locked state. While a non-reentrant lock
 193  * does not strictly require recording of the current owner
 194  * thread, this class does so anyway to make usage easier to monitor.
 195  * It also supports conditions and exposes
 196  * one of the instrumentation methods:
 197  *
 198  *  <pre> {@code
 199  * class Mutex implements Lock, java.io.Serializable {
 200  *
 201  *   // Our internal helper class
 202  *   private static class Sync extends AbstractQueuedSynchronizer {
 203  *     // Reports whether in locked state
 204  *     protected boolean isHeldExclusively() {
 205  *       return getState() == 1;
 206  *     }
 207  *
 208  *     // Acquires the lock if state is zero
 209  *     public boolean tryAcquire(int acquires) {
 210  *       assert acquires == 1; // Otherwise unused
 211  *       if (compareAndSetState(0, 1)) {
 212  *         setExclusiveOwnerThread(Thread.currentThread());
 213  *         return true;
 214  *       }
 215  *       return false;
 216  *     }
 217  *
 218  *     // Releases the lock by setting state to zero
 219  *     protected boolean tryRelease(int releases) {
 220  *       assert releases == 1; // Otherwise unused
 221  *       if (getState() == 0) throw new IllegalMonitorStateException();
 222  *       setExclusiveOwnerThread(null);
 223  *       setState(0);
 224  *       return true;
 225  *     }
 226  *
 227  *     // Provides a Condition
 228  *     Condition newCondition() { return new ConditionObject(); }
 229  *
 230  *     // Deserializes properly
 231  *     private void readObject(ObjectInputStream s)
 232  *         throws IOException, ClassNotFoundException {
 233  *       s.defaultReadObject();
 234  *       setState(0); // reset to unlocked state
 235  *     }
 236  *   }
 237  *
 238  *   // The sync object does all the hard work. We just forward to it.
 239  *   private final Sync sync = new Sync();
 240  *
 241  *   public void lock()                { sync.acquire(1); }
 242  *   public boolean tryLock()          { return sync.tryAcquire(1); }
 243  *   public void unlock()              { sync.release(1); }
 244  *   public Condition newCondition()   { return sync.newCondition(); }
 245  *   public boolean isLocked()         { return sync.isHeldExclusively(); }
 246  *   public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); }
 247  *   public void lockInterruptibly() throws InterruptedException {
 248  *     sync.acquireInterruptibly(1);
 249  *   }
 250  *   public boolean tryLock(long timeout, TimeUnit unit)
 251  *       throws InterruptedException {
 252  *     return sync.tryAcquireNanos(1, unit.toNanos(timeout));
 253  *   }
 254  * }}</pre>
 255  *
 256  * <p>Here is a latch class that is like a
 257  * {@link java.util.concurrent.CountDownLatch CountDownLatch}
 258  * except that it only requires a single {@code signal} to
 259  * fire. Because a latch is non-exclusive, it uses the {@code shared}
 260  * acquire and release methods.
 261  *
 262  *  <pre> {@code
 263  * class BooleanLatch {
 264  *
 265  *   private static class Sync extends AbstractQueuedSynchronizer {
 266  *     boolean isSignalled() { return getState() != 0; }
 267  *
 268  *     protected int tryAcquireShared(int ignore) {
 269  *       return isSignalled() ? 1 : -1;
 270  *     }
 271  *
 272  *     protected boolean tryReleaseShared(int ignore) {
 273  *       setState(1);
 274  *       return true;
 275  *     }
 276  *   }
 277  *
 278  *   private final Sync sync = new Sync();
 279  *   public boolean isSignalled() { return sync.isSignalled(); }
 280  *   public void signal()         { sync.releaseShared(1); }
 281  *   public void await() throws InterruptedException {
 282  *     sync.acquireSharedInterruptibly(1);
 283  *   }
 284  * }}</pre>
 285  *
 286  * @since 1.5
 287  * @author Doug Lea
 288  */
 289 public abstract class AbstractQueuedSynchronizer
 290     extends AbstractOwnableSynchronizer
 291     implements java.io.Serializable {
 292 
 293     private static final long serialVersionUID = 7373984972572414691L;
 294 
 295     /**
 296      * Creates a new {@code AbstractQueuedSynchronizer} instance
 297      * with initial synchronization state of zero.
 298      */
 299     protected AbstractQueuedSynchronizer() { }
 300 
 301     /**
 302      * Wait queue node class.
 303      *
 304      * <p>The wait queue is a variant of a "CLH" (Craig, Landin, and
 305      * Hagersten) lock queue. CLH locks are normally used for
 306      * spinlocks.  We instead use them for blocking synchronizers, but
 307      * use the same basic tactic of holding some of the control
 308      * information about a thread in the predecessor of its node.  A
 309      * "status" field in each node keeps track of whether a thread
 310      * should block.  A node is signalled when its predecessor
 311      * releases.  Each node of the queue otherwise serves as a
 312      * specific-notification-style monitor holding a single waiting
 313      * thread. The status field does NOT control whether threads are
 314      * granted locks etc though.  A thread may try to acquire if it is
 315      * first in the queue. But being first does not guarantee success;
 316      * it only gives the right to contend.  So the currently released
 317      * contender thread may need to rewait.
 318      *
 319      * <p>To enqueue into a CLH lock, you atomically splice it in as new
 320      * tail. To dequeue, you just set the head field.
 321      * <pre>
 322      *      +------+  prev +-----+       +-----+
 323      * head |      | <---- |     | <---- |     |  tail
 324      *      +------+       +-----+       +-----+
 325      * </pre>
 326      *
 327      * <p>Insertion into a CLH queue requires only a single atomic
 328      * operation on "tail", so there is a simple atomic point of
 329      * demarcation from unqueued to queued. Similarly, dequeuing
 330      * involves only updating the "head". However, it takes a bit
 331      * more work for nodes to determine who their successors are,
 332      * in part to deal with possible cancellation due to timeouts
 333      * and interrupts.
 334      *
 335      * <p>The "prev" links (not used in original CLH locks), are mainly
 336      * needed to handle cancellation. If a node is cancelled, its
 337      * successor is (normally) relinked to a non-cancelled
 338      * predecessor. For explanation of similar mechanics in the case
 339      * of spin locks, see the papers by Scott and Scherer at
 340      * http://www.cs.rochester.edu/u/scott/synchronization/
 341      *
 342      * <p>We also use "next" links to implement blocking mechanics.
 343      * The thread id for each node is kept in its own node, so a
 344      * predecessor signals the next node to wake up by traversing
 345      * next link to determine which thread it is.  Determination of
 346      * successor must avoid races with newly queued nodes to set
 347      * the "next" fields of their predecessors.  This is solved
 348      * when necessary by checking backwards from the atomically
 349      * updated "tail" when a node's successor appears to be null.
 350      * (Or, said differently, the next-links are an optimization
 351      * so that we don't usually need a backward scan.)
 352      *
 353      * <p>Cancellation introduces some conservatism to the basic
 354      * algorithms.  Since we must poll for cancellation of other
 355      * nodes, we can miss noticing whether a cancelled node is
 356      * ahead or behind us. This is dealt with by always unparking
 357      * successors upon cancellation, allowing them to stabilize on
 358      * a new predecessor, unless we can identify an uncancelled
 359      * predecessor who will carry this responsibility.
 360      *
 361      * <p>CLH queues need a dummy header node to get started. But
 362      * we don't create them on construction, because it would be wasted
 363      * effort if there is never contention. Instead, the node
 364      * is constructed and head and tail pointers are set upon first
 365      * contention.
 366      *
 367      * <p>Threads waiting on Conditions use the same nodes, but
 368      * use an additional link. Conditions only need to link nodes
 369      * in simple (non-concurrent) linked queues because they are
 370      * only accessed when exclusively held.  Upon await, a node is
 371      * inserted into a condition queue.  Upon signal, the node is
 372      * transferred to the main queue.  A special value of status
 373      * field is used to mark which queue a node is on.
 374      *
 375      * <p>Thanks go to Dave Dice, Mark Moir, Victor Luchangco, Bill
 376      * Scherer and Michael Scott, along with members of JSR-166
 377      * expert group, for helpful ideas, discussions, and critiques
 378      * on the design of this class.
 379      */
 380     static final class Node {
 381         /** Marker to indicate a node is waiting in shared mode */
 382         static final Node SHARED = new Node();
 383         /** Marker to indicate a node is waiting in exclusive mode */
 384         static final Node EXCLUSIVE = null;
 385 
 386         /** waitStatus value to indicate thread has cancelled */
 387         static final int CANCELLED =  1;
 388         /** waitStatus value to indicate successor's thread needs unparking */
 389         static final int SIGNAL    = -1;
 390         /** waitStatus value to indicate thread is waiting on condition */
 391         static final int CONDITION = -2;
 392         /**
 393          * waitStatus value to indicate the next acquireShared should
 394          * unconditionally propagate
 395          */
 396         static final int PROPAGATE = -3;
 397 
 398         /**
 399          * Status field, taking on only the values:
 400          *   SIGNAL:     The successor of this node is (or will soon be)
 401          *               blocked (via park), so the current node must
 402          *               unpark its successor when it releases or
 403          *               cancels. To avoid races, acquire methods must
 404          *               first indicate they need a signal,
 405          *               then retry the atomic acquire, and then,
 406          *               on failure, block.
 407          *   CANCELLED:  This node is cancelled due to timeout or interrupt.
 408          *               Nodes never leave this state. In particular,
 409          *               a thread with cancelled node never again blocks.
 410          *   CONDITION:  This node is currently on a condition queue.
 411          *               It will not be used as a sync queue node
 412          *               until transferred, at which time the status
 413          *               will be set to 0. (Use of this value here has
 414          *               nothing to do with the other uses of the
 415          *               field, but simplifies mechanics.)
 416          *   PROPAGATE:  A releaseShared should be propagated to other
 417          *               nodes. This is set (for head node only) in
 418          *               doReleaseShared to ensure propagation
 419          *               continues, even if other operations have
 420          *               since intervened.
 421          *   0:          None of the above
 422          *
 423          * The values are arranged numerically to simplify use.
 424          * Non-negative values mean that a node doesn't need to
 425          * signal. So, most code doesn't need to check for particular
 426          * values, just for sign.
 427          *
 428          * The field is initialized to 0 for normal sync nodes, and
 429          * CONDITION for condition nodes.  It is modified using CAS
 430          * (or when possible, unconditional volatile writes).
 431          */
 432         volatile int waitStatus;
 433 
 434         /**
 435          * Link to predecessor node that current node/thread relies on
 436          * for checking waitStatus. Assigned during enqueuing, and nulled
 437          * out (for sake of GC) only upon dequeuing.  Also, upon
 438          * cancellation of a predecessor, we short-circuit while
 439          * finding a non-cancelled one, which will always exist
 440          * because the head node is never cancelled: A node becomes
 441          * head only as a result of successful acquire. A
 442          * cancelled thread never succeeds in acquiring, and a thread only
 443          * cancels itself, not any other node.
 444          */
 445         volatile Node prev;
 446 
 447         /**
 448          * Link to the successor node that the current node/thread
 449          * unparks upon release. Assigned during enqueuing, adjusted
 450          * when bypassing cancelled predecessors, and nulled out (for
 451          * sake of GC) when dequeued.  The enq operation does not
 452          * assign next field of a predecessor until after attachment,
 453          * so seeing a null next field does not necessarily mean that
 454          * node is at end of queue. However, if a next field appears
 455          * to be null, we can scan prev's from the tail to
 456          * double-check.  The next field of cancelled nodes is set to
 457          * point to the node itself instead of null, to make life
 458          * easier for isOnSyncQueue.
 459          */
 460         volatile Node next;
 461 
 462         /**
 463          * The thread that enqueued this node.  Initialized on
 464          * construction and nulled out after use.
 465          */
 466         volatile Thread thread;
 467 
 468         /**
 469          * Link to next node waiting on condition, or the special
 470          * value SHARED.  Because condition queues are accessed only
 471          * when holding in exclusive mode, we just need a simple
 472          * linked queue to hold nodes while they are waiting on
 473          * conditions. They are then transferred to the queue to
 474          * re-acquire. And because conditions can only be exclusive,
 475          * we save a field by using special value to indicate shared
 476          * mode.
 477          */
 478         Node nextWaiter;
 479 
 480         /**
 481          * Returns true if node is waiting in shared mode.
 482          */
 483         final boolean isShared() {
 484             return nextWaiter == SHARED;
 485         }
 486 
 487         /**
 488          * Returns previous node, or throws NullPointerException if null.
 489          * Use when predecessor cannot be null.  The null check could
 490          * be elided, but is present to help the VM.
 491          *
 492          * @return the predecessor of this node
 493          */
 494         final Node predecessor() throws NullPointerException {
 495             Node p = prev;
 496             if (p == null)
 497                 throw new NullPointerException();
 498             else
 499                 return p;
 500         }
 501 
 502         Node() {    // Used to establish initial head or SHARED marker
 503         }
 504 
 505         Node(Thread thread, Node mode) {     // Used by addWaiter
 506             this.nextWaiter = mode;
 507             this.thread = thread;
 508         }
 509 
 510         Node(Thread thread, int waitStatus) { // Used by Condition
 511             this.waitStatus = waitStatus;
 512             this.thread = thread;
 513         }
 514     }
 515 
 516     /**
 517      * Head of the wait queue, lazily initialized.  Except for
 518      * initialization, it is modified only via method setHead.  Note:
 519      * If head exists, its waitStatus is guaranteed not to be
 520      * CANCELLED.
 521      */
 522     private transient volatile Node head;
 523 
 524     /**
 525      * Tail of the wait queue, lazily initialized.  Modified only via
 526      * method enq to add new wait node.
 527      */
 528     private transient volatile Node tail;
 529 
 530     /**
 531      * The synchronization state.
 532      */
 533     private volatile int state;
 534 
 535     /**
 536      * Returns the current value of synchronization state.
 537      * This operation has memory semantics of a {@code volatile} read.
 538      * @return current state value
 539      */
 540     protected final int getState() {
 541         return state;
 542     }
 543 
 544     /**
 545      * Sets the value of synchronization state.
 546      * This operation has memory semantics of a {@code volatile} write.
 547      * @param newState the new state value
 548      */
 549     protected final void setState(int newState) {
 550         state = newState;
 551     }
 552 
 553     /**
 554      * Atomically sets synchronization state to the given updated
 555      * value if the current state value equals the expected value.
 556      * This operation has memory semantics of a {@code volatile} read
 557      * and write.
 558      *
 559      * @param expect the expected value
 560      * @param update the new value
 561      * @return {@code true} if successful. False return indicates that the actual
 562      *         value was not equal to the expected value.
 563      */
 564     protected final boolean compareAndSetState(int expect, int update) {
 565         // See below for intrinsics setup to support this
 566         return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
 567     }
 568 
 569     // Queuing utilities
 570 
 571     /**
 572      * The number of nanoseconds for which it is faster to spin
 573      * rather than to use timed park. A rough estimate suffices
 574      * to improve responsiveness with very short timeouts.
 575      */
 576     static final long spinForTimeoutThreshold = 1000L;
 577 
 578     /**
 579      * Inserts node into queue, initializing if necessary. See picture above.
 580      * @param node the node to insert
 581      * @return node's predecessor
 582      */
 583     private Node enq(final Node node) {
 584         for (;;) {
 585             Node t = tail;
 586             if (t == null) { // Must initialize
 587                 if (compareAndSetHead(new Node()))
 588                     tail = head;
 589             } else {
 590                 node.prev = t;
 591                 if (compareAndSetTail(t, node)) {
 592                     t.next = node;
 593                     return t;
 594                 }
 595             }
 596         }
 597     }
 598 
 599     /**
 600      * Creates and enqueues node for current thread and given mode.
 601      *
 602      * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
 603      * @return the new node
 604      */
 605     private Node addWaiter(Node mode) {
 606         Node node = new Node(Thread.currentThread(), mode);
 607         // Try the fast path of enq; backup to full enq on failure
 608         Node pred = tail;
 609         if (pred != null) {
 610             node.prev = pred;
 611             if (compareAndSetTail(pred, node)) {
 612                 pred.next = node;
 613                 return node;
 614             }
 615         }
 616         enq(node);
 617         return node;
 618     }
 619 
 620     /**
 621      * Sets head of queue to be node, thus dequeuing. Called only by
 622      * acquire methods.  Also nulls out unused fields for sake of GC
 623      * and to suppress unnecessary signals and traversals.
 624      *
 625      * @param node the node
 626      */
 627     private void setHead(Node node) {
 628         head = node;
 629         node.thread = null;
 630         node.prev = null;
 631     }
 632 
 633     /**
 634      * Wakes up node's successor, if one exists.
 635      *
 636      * @param node the node
 637      */
 638     private void unparkSuccessor(Node node) {
 639         /*
 640          * If status is negative (i.e., possibly needing signal) try
 641          * to clear in anticipation of signalling.  It is OK if this
 642          * fails or if status is changed by waiting thread.
 643          */
 644         int ws = node.waitStatus;
 645         if (ws < 0)
 646             compareAndSetWaitStatus(node, ws, 0);
 647 
 648         /*
 649          * Thread to unpark is held in successor, which is normally
 650          * just the next node.  But if cancelled or apparently null,
 651          * traverse backwards from tail to find the actual
 652          * non-cancelled successor.
 653          */
 654         Node s = node.next;
 655         if (s == null || s.waitStatus > 0) {
 656             s = null;
 657             for (Node t = tail; t != null && t != node; t = t.prev)
 658                 if (t.waitStatus <= 0)
 659                     s = t;
 660         }
 661         if (s != null)
 662             LockSupport.unpark(s.thread);
 663     }
 664 
 665     /**
 666      * Release action for shared mode -- signals successor and ensures
 667      * propagation. (Note: For exclusive mode, release just amounts
 668      * to calling unparkSuccessor of head if it needs signal.)
 669      */
 670     private void doReleaseShared() {
 671         /*
 672          * Ensure that a release propagates, even if there are other
 673          * in-progress acquires/releases.  This proceeds in the usual
 674          * way of trying to unparkSuccessor of head if it needs
 675          * signal. But if it does not, status is set to PROPAGATE to
 676          * ensure that upon release, propagation continues.
 677          * Additionally, we must loop in case a new node is added
 678          * while we are doing this. Also, unlike other uses of
 679          * unparkSuccessor, we need to know if CAS to reset status
 680          * fails, if so rechecking.
 681          */
 682         for (;;) {
 683             Node h = head;
 684             if (h != null && h != tail) {
 685                 int ws = h.waitStatus;
 686                 if (ws == Node.SIGNAL) {
 687                     if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
 688                         continue;            // loop to recheck cases
 689                     unparkSuccessor(h);
 690                 }
 691                 else if (ws == 0 &&
 692                          !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
 693                     continue;                // loop on failed CAS
 694             }
 695             if (h == head)                   // loop if head changed
 696                 break;
 697         }
 698     }
 699 
 700     /**
 701      * Sets head of queue, and checks if successor may be waiting
 702      * in shared mode, if so propagating if either propagate > 0 or
 703      * PROPAGATE status was set.
 704      *
 705      * @param node the node
 706      * @param propagate the return value from a tryAcquireShared
 707      */
 708     private void setHeadAndPropagate(Node node, int propagate) {
 709         Node h = head; // Record old head for check below
 710         setHead(node);
 711         /*
 712          * Try to signal next queued node if:
 713          *   Propagation was indicated by caller,
 714          *     or was recorded (as h.waitStatus either before
 715          *     or after setHead) by a previous operation
 716          *     (note: this uses sign-check of waitStatus because
 717          *      PROPAGATE status may transition to SIGNAL.)
 718          * and
 719          *   The next node is waiting in shared mode,
 720          *     or we don't know, because it appears null
 721          *
 722          * The conservatism in both of these checks may cause
 723          * unnecessary wake-ups, but only when there are multiple
 724          * racing acquires/releases, so most need signals now or soon
 725          * anyway.
 726          */
 727         if (propagate > 0 || h == null || h.waitStatus < 0 ||
 728             (h = head) == null || h.waitStatus < 0) {
 729             Node s = node.next;
 730             if (s == null || s.isShared())
 731                 doReleaseShared();
 732         }
 733     }
 734 
 735     // Utilities for various versions of acquire
 736 
 737     /**
 738      * Cancels an ongoing attempt to acquire.
 739      *
 740      * @param node the node
 741      */
 742     private void cancelAcquire(Node node) {
 743         // Ignore if node doesn't exist
 744         if (node == null)
 745             return;
 746 
 747         node.thread = null;
 748 
 749         // Skip cancelled predecessors
 750         Node pred = node.prev;
 751         while (pred.waitStatus > 0)
 752             node.prev = pred = pred.prev;
 753 
 754         // predNext is the apparent node to unsplice. CASes below will
 755         // fail if not, in which case, we lost race vs another cancel
 756         // or signal, so no further action is necessary.
 757         Node predNext = pred.next;
 758 
 759         // Can use unconditional write instead of CAS here.
 760         // After this atomic step, other Nodes can skip past us.
 761         // Before, we are free of interference from other threads.
 762         node.waitStatus = Node.CANCELLED;
 763 
 764         // If we are the tail, remove ourselves.
 765         if (node == tail && compareAndSetTail(node, pred)) {
 766             compareAndSetNext(pred, predNext, null);
 767         } else {
 768             // If successor needs signal, try to set pred's next-link
 769             // so it will get one. Otherwise wake it up to propagate.
 770             int ws;
 771             if (pred != head &&
 772                 ((ws = pred.waitStatus) == Node.SIGNAL ||
 773                  (ws <= 0 && compareAndSetWaitStatus(pred, ws, Node.SIGNAL))) &&
 774                 pred.thread != null) {
 775                 Node next = node.next;
 776                 if (next != null && next.waitStatus <= 0)
 777                     compareAndSetNext(pred, predNext, next);
 778             } else {
 779                 unparkSuccessor(node);
 780             }
 781 
 782             node.next = node; // help GC
 783         }
 784     }
 785 
 786     /**
 787      * Checks and updates status for a node that failed to acquire.
 788      * Returns true if thread should block. This is the main signal
 789      * control in all acquire loops.  Requires that pred == node.prev.
 790      *
 791      * @param pred node's predecessor holding status
 792      * @param node the node
 793      * @return {@code true} if thread should block
 794      */
 795     private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
 796         int ws = pred.waitStatus;
 797         if (ws == Node.SIGNAL)
 798             /*
 799              * This node has already set status asking a release
 800              * to signal it, so it can safely park.
 801              */
 802             return true;
 803         if (ws > 0) {
 804             /*
 805              * Predecessor was cancelled. Skip over predecessors and
 806              * indicate retry.
 807              */
 808             do {
 809                 node.prev = pred = pred.prev;
 810             } while (pred.waitStatus > 0);
 811             pred.next = node;
 812         } else {
 813             /*
 814              * waitStatus must be 0 or PROPAGATE.  Indicate that we
 815              * need a signal, but don't park yet.  Caller will need to
 816              * retry to make sure it cannot acquire before parking.
 817              */
 818             compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
 819         }
 820         return false;
 821     }
 822 
 823     /**
 824      * Convenience method to interrupt current thread.
 825      */
 826     static void selfInterrupt() {
 827         Thread.currentThread().interrupt();
 828     }
 829 
 830     /**
 831      * Convenience method to park and then check if interrupted
 832      *
 833      * @return {@code true} if interrupted
 834      */
 835     private final boolean parkAndCheckInterrupt() {
 836         LockSupport.park(this);
 837         return Thread.interrupted();
 838     }
 839 
 840     /*
 841      * Various flavors of acquire, varying in exclusive/shared and
 842      * control modes.  Each is mostly the same, but annoyingly
 843      * different.  Only a little bit of factoring is possible due to
 844      * interactions of exception mechanics (including ensuring that we
 845      * cancel if tryAcquire throws exception) and other control, at
 846      * least not without hurting performance too much.
 847      */
 848 
 849     /**
 850      * Acquires in exclusive uninterruptible mode for thread already in
 851      * queue. Used by condition wait methods as well as acquire.
 852      *
 853      * @param node the node
 854      * @param arg the acquire argument
 855      * @return {@code true} if interrupted while waiting
 856      */
 857     final boolean acquireQueued(final Node node, int arg) {
 858         boolean failed = true;
 859         try {
 860             boolean interrupted = false;
 861             for (;;) {
 862                 final Node p = node.predecessor();
 863                 if (p == head && tryAcquire(arg)) {
 864                     setHead(node);
 865                     p.next = null; // help GC
 866                     failed = false;
 867                     return interrupted;
 868                 }
 869                 if (shouldParkAfterFailedAcquire(p, node) &&
 870                     parkAndCheckInterrupt())
 871                     interrupted = true;
 872             }
 873         } finally {
 874             if (failed)
 875                 cancelAcquire(node);
 876         }
 877     }
 878 
 879     /**
 880      * Acquires in exclusive interruptible mode.
 881      * @param arg the acquire argument
 882      */
 883     private void doAcquireInterruptibly(int arg)
 884         throws InterruptedException {
 885         final Node node = addWaiter(Node.EXCLUSIVE);
 886         boolean failed = true;
 887         try {
 888             for (;;) {
 889                 final Node p = node.predecessor();
 890                 if (p == head && tryAcquire(arg)) {
 891                     setHead(node);
 892                     p.next = null; // help GC
 893                     failed = false;
 894                     return;
 895                 }
 896                 if (shouldParkAfterFailedAcquire(p, node) &&
 897                     parkAndCheckInterrupt())
 898                     throw new InterruptedException();
 899             }
 900         } finally {
 901             if (failed)
 902                 cancelAcquire(node);
 903         }
 904     }
 905 
 906     /**
 907      * Acquires in exclusive timed mode.
 908      *
 909      * @param arg the acquire argument
 910      * @param nanosTimeout max wait time
 911      * @return {@code true} if acquired
 912      */
 913     private boolean doAcquireNanos(int arg, long nanosTimeout)
 914             throws InterruptedException {
 915         if (nanosTimeout <= 0L)
 916             return false;
 917         final long deadline = System.nanoTime() + nanosTimeout;
 918         final Node node = addWaiter(Node.EXCLUSIVE);
 919         boolean failed = true;
 920         try {
 921             for (;;) {
 922                 final Node p = node.predecessor();
 923                 if (p == head && tryAcquire(arg)) {
 924                     setHead(node);
 925                     p.next = null; // help GC
 926                     failed = false;
 927                     return true;
 928                 }
 929                 nanosTimeout = deadline - System.nanoTime();
 930                 if (nanosTimeout <= 0L)
 931                     return false;
 932                 if (shouldParkAfterFailedAcquire(p, node) &&
 933                     nanosTimeout > spinForTimeoutThreshold)
 934                     LockSupport.parkNanos(this, nanosTimeout);
 935                 if (Thread.interrupted())
 936                     throw new InterruptedException();
 937             }
 938         } finally {
 939             if (failed)
 940                 cancelAcquire(node);
 941         }
 942     }
 943 
 944     /**
 945      * Acquires in shared uninterruptible mode.
 946      * @param arg the acquire argument
 947      */
 948     private void doAcquireShared(int arg) {
 949         final Node node = addWaiter(Node.SHARED);
 950         boolean failed = true;
 951         try {
 952             boolean interrupted = false;
 953             for (;;) {
 954                 final Node p = node.predecessor();
 955                 if (p == head) {
 956                     int r = tryAcquireShared(arg);
 957                     if (r >= 0) {
 958                         setHeadAndPropagate(node, r);
 959                         p.next = null; // help GC
 960                         if (interrupted)
 961                             selfInterrupt();
 962                         failed = false;
 963                         return;
 964                     }
 965                 }
 966                 if (shouldParkAfterFailedAcquire(p, node) &&
 967                     parkAndCheckInterrupt())
 968                     interrupted = true;
 969             }
 970         } finally {
 971             if (failed)
 972                 cancelAcquire(node);
 973         }
 974     }
 975 
 976     /**
 977      * Acquires in shared interruptible mode.
 978      * @param arg the acquire argument
 979      */
 980     private void doAcquireSharedInterruptibly(int arg)
 981         throws InterruptedException {
 982         final Node node = addWaiter(Node.SHARED);
 983         boolean failed = true;
 984         try {
 985             for (;;) {
 986                 final Node p = node.predecessor();
 987                 if (p == head) {
 988                     int r = tryAcquireShared(arg);
 989                     if (r >= 0) {
 990                         setHeadAndPropagate(node, r);
 991                         p.next = null; // help GC
 992                         failed = false;
 993                         return;
 994                     }
 995                 }
 996                 if (shouldParkAfterFailedAcquire(p, node) &&
 997                     parkAndCheckInterrupt())
 998                     throw new InterruptedException();
 999             }
1000         } finally {
1001             if (failed)
1002                 cancelAcquire(node);
1003         }
1004     }
1005 
1006     /**
1007      * Acquires in shared timed mode.
1008      *
1009      * @param arg the acquire argument
1010      * @param nanosTimeout max wait time
1011      * @return {@code true} if acquired
1012      */
1013     private boolean doAcquireSharedNanos(int arg, long nanosTimeout)
1014             throws InterruptedException {
1015         if (nanosTimeout <= 0L)
1016             return false;
1017         final long deadline = System.nanoTime() + nanosTimeout;
1018         final Node node = addWaiter(Node.SHARED);
1019         boolean failed = true;
1020         try {
1021             for (;;) {
1022                 final Node p = node.predecessor();
1023                 if (p == head) {
1024                     int r = tryAcquireShared(arg);
1025                     if (r >= 0) {
1026                         setHeadAndPropagate(node, r);
1027                         p.next = null; // help GC
1028                         failed = false;
1029                         return true;
1030                     }
1031                 }
1032                 nanosTimeout = deadline - System.nanoTime();
1033                 if (nanosTimeout <= 0L)
1034                     return false;
1035                 if (shouldParkAfterFailedAcquire(p, node) &&
1036                     nanosTimeout > spinForTimeoutThreshold)
1037                     LockSupport.parkNanos(this, nanosTimeout);
1038                 if (Thread.interrupted())
1039                     throw new InterruptedException();
1040             }
1041         } finally {
1042             if (failed)
1043                 cancelAcquire(node);
1044         }
1045     }
1046 
1047     // Main exported methods
1048 
1049     /**
1050      * Attempts to acquire in exclusive mode. This method should query
1051      * if the state of the object permits it to be acquired in the
1052      * exclusive mode, and if so to acquire it.
1053      *
1054      * <p>This method is always invoked by the thread performing
1055      * acquire.  If this method reports failure, the acquire method
1056      * may queue the thread, if it is not already queued, until it is
1057      * signalled by a release from some other thread. This can be used
1058      * to implement method {@link Lock#tryLock()}.
1059      *
1060      * <p>The default
1061      * implementation throws {@link UnsupportedOperationException}.
1062      *
1063      * @param arg the acquire argument. This value is always the one
1064      *        passed to an acquire method, or is the value saved on entry
1065      *        to a condition wait.  The value is otherwise uninterpreted
1066      *        and can represent anything you like.
1067      * @return {@code true} if successful. Upon success, this object has
1068      *         been acquired.
1069      * @throws IllegalMonitorStateException if acquiring would place this
1070      *         synchronizer in an illegal state. This exception must be
1071      *         thrown in a consistent fashion for synchronization to work
1072      *         correctly.
1073      * @throws UnsupportedOperationException if exclusive mode is not supported
1074      */
1075     protected boolean tryAcquire(int arg) {
1076         throw new UnsupportedOperationException();
1077     }
1078 
1079     /**
1080      * Attempts to set the state to reflect a release in exclusive
1081      * mode.
1082      *
1083      * <p>This method is always invoked by the thread performing release.
1084      *
1085      * <p>The default implementation throws
1086      * {@link UnsupportedOperationException}.
1087      *
1088      * @param arg the release argument. This value is always the one
1089      *        passed to a release method, or the current state value upon
1090      *        entry to a condition wait.  The value is otherwise
1091      *        uninterpreted and can represent anything you like.
1092      * @return {@code true} if this object is now in a fully released
1093      *         state, so that any waiting threads may attempt to acquire;
1094      *         and {@code false} otherwise.
1095      * @throws IllegalMonitorStateException if releasing would place this
1096      *         synchronizer in an illegal state. This exception must be
1097      *         thrown in a consistent fashion for synchronization to work
1098      *         correctly.
1099      * @throws UnsupportedOperationException if exclusive mode is not supported
1100      */
1101     protected boolean tryRelease(int arg) {
1102         throw new UnsupportedOperationException();
1103     }
1104 
1105     /**
1106      * Attempts to acquire in shared mode. This method should query if
1107      * the state of the object permits it to be acquired in the shared
1108      * mode, and if so to acquire it.
1109      *
1110      * <p>This method is always invoked by the thread performing
1111      * acquire.  If this method reports failure, the acquire method
1112      * may queue the thread, if it is not already queued, until it is
1113      * signalled by a release from some other thread.
1114      *
1115      * <p>The default implementation throws {@link
1116      * UnsupportedOperationException}.
1117      *
1118      * @param arg the acquire argument. This value is always the one
1119      *        passed to an acquire method, or is the value saved on entry
1120      *        to a condition wait.  The value is otherwise uninterpreted
1121      *        and can represent anything you like.
1122      * @return a negative value on failure; zero if acquisition in shared
1123      *         mode succeeded but no subsequent shared-mode acquire can
1124      *         succeed; and a positive value if acquisition in shared
1125      *         mode succeeded and subsequent shared-mode acquires might
1126      *         also succeed, in which case a subsequent waiting thread
1127      *         must check availability. (Support for three different
1128      *         return values enables this method to be used in contexts
1129      *         where acquires only sometimes act exclusively.)  Upon
1130      *         success, this object has been acquired.
1131      * @throws IllegalMonitorStateException if acquiring would place this
1132      *         synchronizer in an illegal state. This exception must be
1133      *         thrown in a consistent fashion for synchronization to work
1134      *         correctly.
1135      * @throws UnsupportedOperationException if shared mode is not supported
1136      */
1137     protected int tryAcquireShared(int arg) {
1138         throw new UnsupportedOperationException();
1139     }
1140 
1141     /**
1142      * Attempts to set the state to reflect a release in shared mode.
1143      *
1144      * <p>This method is always invoked by the thread performing release.
1145      *
1146      * <p>The default implementation throws
1147      * {@link UnsupportedOperationException}.
1148      *
1149      * @param arg the release argument. This value is always the one
1150      *        passed to a release method, or the current state value upon
1151      *        entry to a condition wait.  The value is otherwise
1152      *        uninterpreted and can represent anything you like.
1153      * @return {@code true} if this release of shared mode may permit a
1154      *         waiting acquire (shared or exclusive) to succeed; and
1155      *         {@code false} otherwise
1156      * @throws IllegalMonitorStateException if releasing would place this
1157      *         synchronizer in an illegal state. This exception must be
1158      *         thrown in a consistent fashion for synchronization to work
1159      *         correctly.
1160      * @throws UnsupportedOperationException if shared mode is not supported
1161      */
1162     protected boolean tryReleaseShared(int arg) {
1163         throw new UnsupportedOperationException();
1164     }
1165 
1166     /**
1167      * Returns {@code true} if synchronization is held exclusively with
1168      * respect to the current (calling) thread.  This method is invoked
1169      * upon each call to a non-waiting {@link ConditionObject} method.
1170      * (Waiting methods instead invoke {@link #release}.)
1171      *
1172      * <p>The default implementation throws {@link
1173      * UnsupportedOperationException}. This method is invoked
1174      * internally only within {@link ConditionObject} methods, so need
1175      * not be defined if conditions are not used.
1176      *
1177      * @return {@code true} if synchronization is held exclusively;
1178      *         {@code false} otherwise
1179      * @throws UnsupportedOperationException if conditions are not supported
1180      */
1181     protected boolean isHeldExclusively() {
1182         throw new UnsupportedOperationException();
1183     }
1184 
1185     /**
1186      * Acquires in exclusive mode, ignoring interrupts.  Implemented
1187      * by invoking at least once {@link #tryAcquire},
1188      * returning on success.  Otherwise the thread is queued, possibly
1189      * repeatedly blocking and unblocking, invoking {@link
1190      * #tryAcquire} until success.  This method can be used
1191      * to implement method {@link Lock#lock}.
1192      *
1193      * @param arg the acquire argument.  This value is conveyed to
1194      *        {@link #tryAcquire} but is otherwise uninterpreted and
1195      *        can represent anything you like.
1196      */
1197     public final void acquire(int arg) {
1198         if (!tryAcquire(arg) &&
1199             acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
1200             selfInterrupt();
1201     }
1202 
1203     /**
1204      * Acquires in exclusive mode, aborting if interrupted.
1205      * Implemented by first checking interrupt status, then invoking
1206      * at least once {@link #tryAcquire}, returning on
1207      * success.  Otherwise the thread is queued, possibly repeatedly
1208      * blocking and unblocking, invoking {@link #tryAcquire}
1209      * until success or the thread is interrupted.  This method can be
1210      * used to implement method {@link Lock#lockInterruptibly}.
1211      *
1212      * @param arg the acquire argument.  This value is conveyed to
1213      *        {@link #tryAcquire} but is otherwise uninterpreted and
1214      *        can represent anything you like.
1215      * @throws InterruptedException if the current thread is interrupted
1216      */
1217     public final void acquireInterruptibly(int arg)
1218             throws InterruptedException {
1219         if (Thread.interrupted())
1220             throw new InterruptedException();
1221         if (!tryAcquire(arg))
1222             doAcquireInterruptibly(arg);
1223     }
1224 
1225     /**
1226      * Attempts to acquire in exclusive mode, aborting if interrupted,
1227      * and failing if the given timeout elapses.  Implemented by first
1228      * checking interrupt status, then invoking at least once {@link
1229      * #tryAcquire}, returning on success.  Otherwise, the thread is
1230      * queued, possibly repeatedly blocking and unblocking, invoking
1231      * {@link #tryAcquire} until success or the thread is interrupted
1232      * or the timeout elapses.  This method can be used to implement
1233      * method {@link Lock#tryLock(long, TimeUnit)}.
1234      *
1235      * @param arg the acquire argument.  This value is conveyed to
1236      *        {@link #tryAcquire} but is otherwise uninterpreted and
1237      *        can represent anything you like.
1238      * @param nanosTimeout the maximum number of nanoseconds to wait
1239      * @return {@code true} if acquired; {@code false} if timed out
1240      * @throws InterruptedException if the current thread is interrupted
1241      */
1242     public final boolean tryAcquireNanos(int arg, long nanosTimeout)
1243             throws InterruptedException {
1244         if (Thread.interrupted())
1245             throw new InterruptedException();
1246         return tryAcquire(arg) ||
1247             doAcquireNanos(arg, nanosTimeout);
1248     }
1249 
1250     /**
1251      * Releases in exclusive mode.  Implemented by unblocking one or
1252      * more threads if {@link #tryRelease} returns true.
1253      * This method can be used to implement method {@link Lock#unlock}.
1254      *
1255      * @param arg the release argument.  This value is conveyed to
1256      *        {@link #tryRelease} but is otherwise uninterpreted and
1257      *        can represent anything you like.
1258      * @return the value returned from {@link #tryRelease}
1259      */
1260     public final boolean release(int arg) {
1261         if (tryRelease(arg)) {
1262             Node h = head;
1263             if (h != null && h.waitStatus != 0)
1264                 unparkSuccessor(h);
1265             return true;
1266         }
1267         return false;
1268     }
1269 
1270     /**
1271      * Acquires in shared mode, ignoring interrupts.  Implemented by
1272      * first invoking at least once {@link #tryAcquireShared},
1273      * returning on success.  Otherwise the thread is queued, possibly
1274      * repeatedly blocking and unblocking, invoking {@link
1275      * #tryAcquireShared} until success.
1276      *
1277      * @param arg the acquire argument.  This value is conveyed to
1278      *        {@link #tryAcquireShared} but is otherwise uninterpreted
1279      *        and can represent anything you like.
1280      */
1281     public final void acquireShared(int arg) {
1282         if (tryAcquireShared(arg) < 0)
1283             doAcquireShared(arg);
1284     }
1285 
1286     /**
1287      * Acquires in shared mode, aborting if interrupted.  Implemented
1288      * by first checking interrupt status, then invoking at least once
1289      * {@link #tryAcquireShared}, returning on success.  Otherwise the
1290      * thread is queued, possibly repeatedly blocking and unblocking,
1291      * invoking {@link #tryAcquireShared} until success or the thread
1292      * is interrupted.
1293      * @param arg the acquire argument.
1294      * This value is conveyed to {@link #tryAcquireShared} but is
1295      * otherwise uninterpreted and can represent anything
1296      * you like.
1297      * @throws InterruptedException if the current thread is interrupted
1298      */
1299     public final void acquireSharedInterruptibly(int arg)
1300             throws InterruptedException {
1301         if (Thread.interrupted())
1302             throw new InterruptedException();
1303         if (tryAcquireShared(arg) < 0)
1304             doAcquireSharedInterruptibly(arg);
1305     }
1306 
1307     /**
1308      * Attempts to acquire in shared mode, aborting if interrupted, and
1309      * failing if the given timeout elapses.  Implemented by first
1310      * checking interrupt status, then invoking at least once {@link
1311      * #tryAcquireShared}, returning on success.  Otherwise, the
1312      * thread is queued, possibly repeatedly blocking and unblocking,
1313      * invoking {@link #tryAcquireShared} until success or the thread
1314      * is interrupted or the timeout elapses.
1315      *
1316      * @param arg the acquire argument.  This value is conveyed to
1317      *        {@link #tryAcquireShared} but is otherwise uninterpreted
1318      *        and can represent anything you like.
1319      * @param nanosTimeout the maximum number of nanoseconds to wait
1320      * @return {@code true} if acquired; {@code false} if timed out
1321      * @throws InterruptedException if the current thread is interrupted
1322      */
1323     public final boolean tryAcquireSharedNanos(int arg, long nanosTimeout)
1324             throws InterruptedException {
1325         if (Thread.interrupted())
1326             throw new InterruptedException();
1327         return tryAcquireShared(arg) >= 0 ||
1328             doAcquireSharedNanos(arg, nanosTimeout);
1329     }
1330 
1331     /**
1332      * Releases in shared mode.  Implemented by unblocking one or more
1333      * threads if {@link #tryReleaseShared} returns true.
1334      *
1335      * @param arg the release argument.  This value is conveyed to
1336      *        {@link #tryReleaseShared} but is otherwise uninterpreted
1337      *        and can represent anything you like.
1338      * @return the value returned from {@link #tryReleaseShared}
1339      */
1340     public final boolean releaseShared(int arg) {
1341         if (tryReleaseShared(arg)) {
1342             doReleaseShared();
1343             return true;
1344         }
1345         return false;
1346     }
1347 
1348     // Queue inspection methods
1349 
1350     /**
1351      * Queries whether any threads are waiting to acquire. Note that
1352      * because cancellations due to interrupts and timeouts may occur
1353      * at any time, a {@code true} return does not guarantee that any
1354      * other thread will ever acquire.
1355      *
1356      * <p>In this implementation, this operation returns in
1357      * constant time.
1358      *
1359      * @return {@code true} if there may be other threads waiting to acquire
1360      */
1361     public final boolean hasQueuedThreads() {
1362         return head != tail;
1363     }
1364 
1365     /**
1366      * Queries whether any threads have ever contended to acquire this
1367      * synchronizer; that is if an acquire method has ever blocked.
1368      *
1369      * <p>In this implementation, this operation returns in
1370      * constant time.
1371      *
1372      * @return {@code true} if there has ever been contention
1373      */
1374     public final boolean hasContended() {
1375         return head != null;
1376     }
1377 
1378     /**
1379      * Returns the first (longest-waiting) thread in the queue, or
1380      * {@code null} if no threads are currently queued.
1381      *
1382      * <p>In this implementation, this operation normally returns in
1383      * constant time, but may iterate upon contention if other threads are
1384      * concurrently modifying the queue.
1385      *
1386      * @return the first (longest-waiting) thread in the queue, or
1387      *         {@code null} if no threads are currently queued
1388      */
1389     public final Thread getFirstQueuedThread() {
1390         // handle only fast path, else relay
1391         return (head == tail) ? null : fullGetFirstQueuedThread();
1392     }
1393 
1394     /**
1395      * Version of getFirstQueuedThread called when fastpath fails
1396      */
1397     private Thread fullGetFirstQueuedThread() {
1398         /*
1399          * The first node is normally head.next. Try to get its
1400          * thread field, ensuring consistent reads: If thread
1401          * field is nulled out or s.prev is no longer head, then
1402          * some other thread(s) concurrently performed setHead in
1403          * between some of our reads. We try this twice before
1404          * resorting to traversal.
1405          */
1406         Node h, s;
1407         Thread st;
1408         if (((h = head) != null && (s = h.next) != null &&
1409              s.prev == head && (st = s.thread) != null) ||
1410             ((h = head) != null && (s = h.next) != null &&
1411              s.prev == head && (st = s.thread) != null))
1412             return st;
1413 
1414         /*
1415          * Head's next field might not have been set yet, or may have
1416          * been unset after setHead. So we must check to see if tail
1417          * is actually first node. If not, we continue on, safely
1418          * traversing from tail back to head to find first,
1419          * guaranteeing termination.
1420          */
1421 
1422         Node t = tail;
1423         Thread firstThread = null;
1424         while (t != null && t != head) {
1425             Thread tt = t.thread;
1426             if (tt != null)
1427                 firstThread = tt;
1428             t = t.prev;
1429         }
1430         return firstThread;
1431     }
1432 
1433     /**
1434      * Returns true if the given thread is currently queued.
1435      *
1436      * <p>This implementation traverses the queue to determine
1437      * presence of the given thread.
1438      *
1439      * @param thread the thread
1440      * @return {@code true} if the given thread is on the queue
1441      * @throws NullPointerException if the thread is null
1442      */
1443     public final boolean isQueued(Thread thread) {
1444         if (thread == null)
1445             throw new NullPointerException();
1446         for (Node p = tail; p != null; p = p.prev)
1447             if (p.thread == thread)
1448                 return true;
1449         return false;
1450     }
1451 
1452     /**
1453      * Returns {@code true} if the apparent first queued thread, if one
1454      * exists, is waiting in exclusive mode.  If this method returns
1455      * {@code true}, and the current thread is attempting to acquire in
1456      * shared mode (that is, this method is invoked from {@link
1457      * #tryAcquireShared}) then it is guaranteed that the current thread
1458      * is not the first queued thread.  Used only as a heuristic in
1459      * ReentrantReadWriteLock.
1460      */
1461     final boolean apparentlyFirstQueuedIsExclusive() {
1462         Node h, s;
1463         return (h = head) != null &&
1464             (s = h.next)  != null &&
1465             !s.isShared()         &&
1466             s.thread != null;
1467     }
1468 
1469     /**
1470      * Queries whether any threads have been waiting to acquire longer
1471      * than the current thread.
1472      *
1473      * <p>An invocation of this method is equivalent to (but may be
1474      * more efficient than):
1475      *  <pre> {@code
1476      * getFirstQueuedThread() != Thread.currentThread() &&
1477      * hasQueuedThreads()}</pre>
1478      *
1479      * <p>Note that because cancellations due to interrupts and
1480      * timeouts may occur at any time, a {@code true} return does not
1481      * guarantee that some other thread will acquire before the current
1482      * thread.  Likewise, it is possible for another thread to win a
1483      * race to enqueue after this method has returned {@code false},
1484      * due to the queue being empty.
1485      *
1486      * <p>This method is designed to be used by a fair synchronizer to
1487      * avoid <a href="AbstractQueuedSynchronizer#barging">barging</a>.
1488      * Such a synchronizer's {@link #tryAcquire} method should return
1489      * {@code false}, and its {@link #tryAcquireShared} method should
1490      * return a negative value, if this method returns {@code true}
1491      * (unless this is a reentrant acquire).  For example, the {@code
1492      * tryAcquire} method for a fair, reentrant, exclusive mode
1493      * synchronizer might look like this:
1494      *
1495      *  <pre> {@code
1496      * protected boolean tryAcquire(int arg) {
1497      *   if (isHeldExclusively()) {
1498      *     // A reentrant acquire; increment hold count
1499      *     return true;
1500      *   } else if (hasQueuedPredecessors()) {
1501      *     return false;
1502      *   } else {
1503      *     // try to acquire normally
1504      *   }
1505      * }}</pre>
1506      *
1507      * @return {@code true} if there is a queued thread preceding the
1508      *         current thread, and {@code false} if the current thread
1509      *         is at the head of the queue or the queue is empty
1510      * @since 1.7
1511      */
1512     public final boolean hasQueuedPredecessors() {
1513         // The correctness of this depends on head being initialized
1514         // before tail and on head.next being accurate if the current
1515         // thread is first in queue.
1516         Node t = tail; // Read fields in reverse initialization order
1517         Node h = head;
1518         Node s;
1519         return h != t &&
1520             ((s = h.next) == null || s.thread != Thread.currentThread());
1521     }
1522 
1523 
1524     // Instrumentation and monitoring methods
1525 
1526     /**
1527      * Returns an estimate of the number of threads waiting to
1528      * acquire.  The value is only an estimate because the number of
1529      * threads may change dynamically while this method traverses
1530      * internal data structures.  This method is designed for use in
1531      * monitoring system state, not for synchronization
1532      * control.
1533      *
1534      * @return the estimated number of threads waiting to acquire
1535      */
1536     public final int getQueueLength() {
1537         int n = 0;
1538         for (Node p = tail; p != null; p = p.prev) {
1539             if (p.thread != null)
1540                 ++n;
1541         }
1542         return n;
1543     }
1544 
1545     /**
1546      * Returns a collection containing threads that may be waiting to
1547      * acquire.  Because the actual set of threads may change
1548      * dynamically while constructing this result, the returned
1549      * collection is only a best-effort estimate.  The elements of the
1550      * returned collection are in no particular order.  This method is
1551      * designed to facilitate construction of subclasses that provide
1552      * more extensive monitoring facilities.
1553      *
1554      * @return the collection of threads
1555      */
1556     public final Collection<Thread> getQueuedThreads() {
1557         ArrayList<Thread> list = new ArrayList<Thread>();
1558         for (Node p = tail; p != null; p = p.prev) {
1559             Thread t = p.thread;
1560             if (t != null)
1561                 list.add(t);
1562         }
1563         return list;
1564     }
1565 
1566     /**
1567      * Returns a collection containing threads that may be waiting to
1568      * acquire in exclusive mode. This has the same properties
1569      * as {@link #getQueuedThreads} except that it only returns
1570      * those threads waiting due to an exclusive acquire.
1571      *
1572      * @return the collection of threads
1573      */
1574     public final Collection<Thread> getExclusiveQueuedThreads() {
1575         ArrayList<Thread> list = new ArrayList<Thread>();
1576         for (Node p = tail; p != null; p = p.prev) {
1577             if (!p.isShared()) {
1578                 Thread t = p.thread;
1579                 if (t != null)
1580                     list.add(t);
1581             }
1582         }
1583         return list;
1584     }
1585 
1586     /**
1587      * Returns a collection containing threads that may be waiting to
1588      * acquire in shared mode. This has the same properties
1589      * as {@link #getQueuedThreads} except that it only returns
1590      * those threads waiting due to a shared acquire.
1591      *
1592      * @return the collection of threads
1593      */
1594     public final Collection<Thread> getSharedQueuedThreads() {
1595         ArrayList<Thread> list = new ArrayList<Thread>();
1596         for (Node p = tail; p != null; p = p.prev) {
1597             if (p.isShared()) {
1598                 Thread t = p.thread;
1599                 if (t != null)
1600                     list.add(t);
1601             }
1602         }
1603         return list;
1604     }
1605 
1606     /**
1607      * Returns a string identifying this synchronizer, as well as its state.
1608      * The state, in brackets, includes the String {@code "State ="}
1609      * followed by the current value of {@link #getState}, and either
1610      * {@code "nonempty"} or {@code "empty"} depending on whether the
1611      * queue is empty.
1612      *
1613      * @return a string identifying this synchronizer, as well as its state
1614      */
1615     public String toString() {
1616         int s = getState();
1617         String q  = hasQueuedThreads() ? "non" : "";
1618         return super.toString() +
1619             "[State = " + s + ", " + q + "empty queue]";
1620     }
1621 
1622 
1623     // Internal support methods for Conditions
1624 
1625     /**
1626      * Returns true if a node, always one that was initially placed on
1627      * a condition queue, is now waiting to reacquire on sync queue.
1628      * @param node the node
1629      * @return true if is reacquiring
1630      */
1631     final boolean isOnSyncQueue(Node node) {
1632         if (node.waitStatus == Node.CONDITION || node.prev == null)
1633             return false;
1634         if (node.next != null) // If has successor, it must be on queue
1635             return true;
1636         /*
1637          * node.prev can be non-null, but not yet on queue because
1638          * the CAS to place it on queue can fail. So we have to
1639          * traverse from tail to make sure it actually made it.  It
1640          * will always be near the tail in calls to this method, and
1641          * unless the CAS failed (which is unlikely), it will be
1642          * there, so we hardly ever traverse much.
1643          */
1644         return findNodeFromTail(node);
1645     }
1646 
1647     /**
1648      * Returns true if node is on sync queue by searching backwards from tail.
1649      * Called only when needed by isOnSyncQueue.
1650      * @return true if present
1651      */
1652     private boolean findNodeFromTail(Node node) {
1653         Node t = tail;
1654         for (;;) {
1655             if (t == node)
1656                 return true;
1657             if (t == null)
1658                 return false;
1659             t = t.prev;
1660         }
1661     }
1662 
1663     /**
1664      * Transfers a node from a condition queue onto sync queue.
1665      * Returns true if successful.
1666      * @param node the node
1667      * @return true if successfully transferred (else the node was
1668      * cancelled before signal)
1669      */
1670     final boolean transferForSignal(Node node) {
1671         /*
1672          * If cannot change waitStatus, the node has been cancelled.
1673          */
1674         if (!compareAndSetWaitStatus(node, Node.CONDITION, 0))
1675             return false;
1676 
1677         /*
1678          * Splice onto queue and try to set waitStatus of predecessor to
1679          * indicate that thread is (probably) waiting. If cancelled or
1680          * attempt to set waitStatus fails, wake up to resync (in which
1681          * case the waitStatus can be transiently and harmlessly wrong).
1682          */
1683         Node p = enq(node);
1684         int ws = p.waitStatus;
1685         if (ws > 0 || !compareAndSetWaitStatus(p, ws, Node.SIGNAL))
1686             LockSupport.unpark(node.thread);
1687         return true;
1688     }
1689 
1690     /**
1691      * Transfers node, if necessary, to sync queue after a cancelled wait.
1692      * Returns true if thread was cancelled before being signalled.
1693      *
1694      * @param node the node
1695      * @return true if cancelled before the node was signalled
1696      */
1697     final boolean transferAfterCancelledWait(Node node) {
1698         if (compareAndSetWaitStatus(node, Node.CONDITION, 0)) {
1699             enq(node);
1700             return true;
1701         }
1702         /*
1703          * If we lost out to a signal(), then we can't proceed
1704          * until it finishes its enq().  Cancelling during an
1705          * incomplete transfer is both rare and transient, so just
1706          * spin.
1707          */
1708         while (!isOnSyncQueue(node))
1709             Thread.yield();
1710         return false;
1711     }
1712 
1713     /**
1714      * Invokes release with current state value; returns saved state.
1715      * Cancels node and throws exception on failure.
1716      * @param node the condition node for this wait
1717      * @return previous sync state
1718      */
1719     final int fullyRelease(Node node) {
1720         boolean failed = true;
1721         try {
1722             int savedState = getState();
1723             if (release(savedState)) {
1724                 failed = false;
1725                 return savedState;
1726             } else {
1727                 throw new IllegalMonitorStateException();
1728             }
1729         } finally {
1730             if (failed)
1731                 node.waitStatus = Node.CANCELLED;
1732         }
1733     }
1734 
1735     // Instrumentation methods for conditions
1736 
1737     /**
1738      * Queries whether the given ConditionObject
1739      * uses this synchronizer as its lock.
1740      *
1741      * @param condition the condition
1742      * @return {@code true} if owned
1743      * @throws NullPointerException if the condition is null
1744      */
1745     public final boolean owns(ConditionObject condition) {
1746         return condition.isOwnedBy(this);
1747     }
1748 
1749     /**
1750      * Queries whether any threads are waiting on the given condition
1751      * associated with this synchronizer. Note that because timeouts
1752      * and interrupts may occur at any time, a {@code true} return
1753      * does not guarantee that a future {@code signal} will awaken
1754      * any threads.  This method is designed primarily for use in
1755      * monitoring of the system state.
1756      *
1757      * @param condition the condition
1758      * @return {@code true} if there are any waiting threads
1759      * @throws IllegalMonitorStateException if exclusive synchronization
1760      *         is not held
1761      * @throws IllegalArgumentException if the given condition is
1762      *         not associated with this synchronizer
1763      * @throws NullPointerException if the condition is null
1764      */
1765     public final boolean hasWaiters(ConditionObject condition) {
1766         if (!owns(condition))
1767             throw new IllegalArgumentException("Not owner");
1768         return condition.hasWaiters();
1769     }
1770 
1771     /**
1772      * Returns an estimate of the number of threads waiting on the
1773      * given condition associated with this synchronizer. Note that
1774      * because timeouts and interrupts may occur at any time, the
1775      * estimate serves only as an upper bound on the actual number of
1776      * waiters.  This method is designed for use in monitoring of the
1777      * system state, not for synchronization control.
1778      *
1779      * @param condition the condition
1780      * @return the estimated number of waiting threads
1781      * @throws IllegalMonitorStateException if exclusive synchronization
1782      *         is not held
1783      * @throws IllegalArgumentException if the given condition is
1784      *         not associated with this synchronizer
1785      * @throws NullPointerException if the condition is null
1786      */
1787     public final int getWaitQueueLength(ConditionObject condition) {
1788         if (!owns(condition))
1789             throw new IllegalArgumentException("Not owner");
1790         return condition.getWaitQueueLength();
1791     }
1792 
1793     /**
1794      * Returns a collection containing those threads that may be
1795      * waiting on the given condition associated with this
1796      * synchronizer.  Because the actual set of threads may change
1797      * dynamically while constructing this result, the returned
1798      * collection is only a best-effort estimate. The elements of the
1799      * returned collection are in no particular order.
1800      *
1801      * @param condition the condition
1802      * @return the collection of threads
1803      * @throws IllegalMonitorStateException if exclusive synchronization
1804      *         is not held
1805      * @throws IllegalArgumentException if the given condition is
1806      *         not associated with this synchronizer
1807      * @throws NullPointerException if the condition is null
1808      */
1809     public final Collection<Thread> getWaitingThreads(ConditionObject condition) {
1810         if (!owns(condition))
1811             throw new IllegalArgumentException("Not owner");
1812         return condition.getWaitingThreads();
1813     }
1814 
1815     /**
1816      * Condition implementation for a {@link
1817      * AbstractQueuedSynchronizer} serving as the basis of a {@link
1818      * Lock} implementation.
1819      *
1820      * <p>Method documentation for this class describes mechanics,
1821      * not behavioral specifications from the point of view of Lock
1822      * and Condition users. Exported versions of this class will in
1823      * general need to be accompanied by documentation describing
1824      * condition semantics that rely on those of the associated
1825      * {@code AbstractQueuedSynchronizer}.
1826      *
1827      * <p>This class is Serializable, but all fields are transient,
1828      * so deserialized conditions have no waiters.
1829      */
1830     public class ConditionObject implements Condition, java.io.Serializable {
1831         private static final long serialVersionUID = 1173984872572414699L;
1832         /** First node of condition queue. */
1833         private transient Node firstWaiter;
1834         /** Last node of condition queue. */
1835         private transient Node lastWaiter;
1836 
1837         /**
1838          * Creates a new {@code ConditionObject} instance.
1839          */
1840         public ConditionObject() { }
1841 
1842         // Internal methods
1843 
1844         /**
1845          * Adds a new waiter to wait queue.
1846          * @return its new wait node
1847          */
1848         private Node addConditionWaiter() {
1849             Node t = lastWaiter;
1850             // If lastWaiter is cancelled, clean out.
1851             if (t != null && t.waitStatus != Node.CONDITION) {
1852                 unlinkCancelledWaiters();
1853                 t = lastWaiter;
1854             }
1855             Node node = new Node(Thread.currentThread(), Node.CONDITION);
1856             if (t == null)
1857                 firstWaiter = node;
1858             else
1859                 t.nextWaiter = node;
1860             lastWaiter = node;
1861             return node;
1862         }
1863 
1864         /**
1865          * Removes and transfers nodes until hit non-cancelled one or
1866          * null. Split out from signal in part to encourage compilers
1867          * to inline the case of no waiters.
1868          * @param first (non-null) the first node on condition queue
1869          */
1870         private void doSignal(Node first) {
1871             do {
1872                 if ( (firstWaiter = first.nextWaiter) == null)
1873                     lastWaiter = null;
1874                 first.nextWaiter = null;
1875             } while (!transferForSignal(first) &&
1876                      (first = firstWaiter) != null);
1877         }
1878 
1879         /**
1880          * Removes and transfers all nodes.
1881          * @param first (non-null) the first node on condition queue
1882          */
1883         private void doSignalAll(Node first) {
1884             lastWaiter = firstWaiter = null;
1885             do {
1886                 Node next = first.nextWaiter;
1887                 first.nextWaiter = null;
1888                 transferForSignal(first);
1889                 first = next;
1890             } while (first != null);
1891         }
1892 
1893         /**
1894          * Unlinks cancelled waiter nodes from condition queue.
1895          * Called only while holding lock. This is called when
1896          * cancellation occurred during condition wait, and upon
1897          * insertion of a new waiter when lastWaiter is seen to have
1898          * been cancelled. This method is needed to avoid garbage
1899          * retention in the absence of signals. So even though it may
1900          * require a full traversal, it comes into play only when
1901          * timeouts or cancellations occur in the absence of
1902          * signals. It traverses all nodes rather than stopping at a
1903          * particular target to unlink all pointers to garbage nodes
1904          * without requiring many re-traversals during cancellation
1905          * storms.
1906          */
1907         private void unlinkCancelledWaiters() {
1908             Node t = firstWaiter;
1909             Node trail = null;
1910             while (t != null) {
1911                 Node next = t.nextWaiter;
1912                 if (t.waitStatus != Node.CONDITION) {
1913                     t.nextWaiter = null;
1914                     if (trail == null)
1915                         firstWaiter = next;
1916                     else
1917                         trail.nextWaiter = next;
1918                     if (next == null)
1919                         lastWaiter = trail;
1920                 }
1921                 else
1922                     trail = t;
1923                 t = next;
1924             }
1925         }
1926 
1927         // public methods
1928 
1929         /**
1930          * Moves the longest-waiting thread, if one exists, from the
1931          * wait queue for this condition to the wait queue for the
1932          * owning lock.
1933          *
1934          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1935          *         returns {@code false}
1936          */
1937         public final void signal() {
1938             if (!isHeldExclusively())
1939                 throw new IllegalMonitorStateException();
1940             Node first = firstWaiter;
1941             if (first != null)
1942                 doSignal(first);
1943         }
1944 
1945         /**
1946          * Moves all threads from the wait queue for this condition to
1947          * the wait queue for the owning lock.
1948          *
1949          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
1950          *         returns {@code false}
1951          */
1952         public final void signalAll() {
1953             if (!isHeldExclusively())
1954                 throw new IllegalMonitorStateException();
1955             Node first = firstWaiter;
1956             if (first != null)
1957                 doSignalAll(first);
1958         }
1959 
1960         /**
1961          * Implements uninterruptible condition wait.
1962          * <ol>
1963          * <li> Save lock state returned by {@link #getState}.
1964          * <li> Invoke {@link #release} with saved state as argument,
1965          *      throwing IllegalMonitorStateException if it fails.
1966          * <li> Block until signalled.
1967          * <li> Reacquire by invoking specialized version of
1968          *      {@link #acquire} with saved state as argument.
1969          * </ol>
1970          */
1971         public final void awaitUninterruptibly() {
1972             Node node = addConditionWaiter();
1973             int savedState = fullyRelease(node);
1974             boolean interrupted = false;
1975             while (!isOnSyncQueue(node)) {
1976                 LockSupport.park(this);
1977                 if (Thread.interrupted())
1978                     interrupted = true;
1979             }
1980             if (acquireQueued(node, savedState) || interrupted)
1981                 selfInterrupt();
1982         }
1983 
1984         /*
1985          * For interruptible waits, we need to track whether to throw
1986          * InterruptedException, if interrupted while blocked on
1987          * condition, versus reinterrupt current thread, if
1988          * interrupted while blocked waiting to re-acquire.
1989          */
1990 
1991         /** Mode meaning to reinterrupt on exit from wait */
1992         private static final int REINTERRUPT =  1;
1993         /** Mode meaning to throw InterruptedException on exit from wait */
1994         private static final int THROW_IE    = -1;
1995 
1996         /**
1997          * Checks for interrupt, returning THROW_IE if interrupted
1998          * before signalled, REINTERRUPT if after signalled, or
1999          * 0 if not interrupted.
2000          */
2001         private int checkInterruptWhileWaiting(Node node) {
2002             return Thread.interrupted() ?
2003                 (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) :
2004                 0;
2005         }
2006 
2007         /**
2008          * Throws InterruptedException, reinterrupts current thread, or
2009          * does nothing, depending on mode.
2010          */
2011         private void reportInterruptAfterWait(int interruptMode)
2012             throws InterruptedException {
2013             if (interruptMode == THROW_IE)
2014                 throw new InterruptedException();
2015             else if (interruptMode == REINTERRUPT)
2016                 selfInterrupt();
2017         }
2018 
2019         /**
2020          * Implements interruptible condition wait.
2021          * <ol>
2022          * <li> If current thread is interrupted, throw InterruptedException.
2023          * <li> Save lock state returned by {@link #getState}.
2024          * <li> Invoke {@link #release} with saved state as argument,
2025          *      throwing IllegalMonitorStateException if it fails.
2026          * <li> Block until signalled or interrupted.
2027          * <li> Reacquire by invoking specialized version of
2028          *      {@link #acquire} with saved state as argument.
2029          * <li> If interrupted while blocked in step 4, throw InterruptedException.
2030          * </ol>
2031          */
2032         public final void await() throws InterruptedException {
2033             if (Thread.interrupted())
2034                 throw new InterruptedException();
2035             Node node = addConditionWaiter();
2036             int savedState = fullyRelease(node);
2037             int interruptMode = 0;
2038             while (!isOnSyncQueue(node)) {
2039                 LockSupport.park(this);
2040                 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2041                     break;
2042             }
2043             if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2044                 interruptMode = REINTERRUPT;
2045             if (node.nextWaiter != null) // clean up if cancelled
2046                 unlinkCancelledWaiters();
2047             if (interruptMode != 0)
2048                 reportInterruptAfterWait(interruptMode);
2049         }
2050 
2051         /**
2052          * Implements timed condition wait.
2053          * <ol>
2054          * <li> If current thread is interrupted, throw InterruptedException.
2055          * <li> Save lock state returned by {@link #getState}.
2056          * <li> Invoke {@link #release} with saved state as argument,
2057          *      throwing IllegalMonitorStateException if it fails.
2058          * <li> Block until signalled, interrupted, or timed out.
2059          * <li> Reacquire by invoking specialized version of
2060          *      {@link #acquire} with saved state as argument.
2061          * <li> If interrupted while blocked in step 4, throw InterruptedException.
2062          * </ol>
2063          */
2064         public final long awaitNanos(long nanosTimeout)
2065                 throws InterruptedException {
2066             if (Thread.interrupted())
2067                 throw new InterruptedException();
2068             Node node = addConditionWaiter();
2069             int savedState = fullyRelease(node);
2070             final long deadline = System.nanoTime() + nanosTimeout;
2071             int interruptMode = 0;
2072             while (!isOnSyncQueue(node)) {
2073                 if (nanosTimeout <= 0L) {
2074                     transferAfterCancelledWait(node);
2075                     break;
2076                 }
2077                 if (nanosTimeout >= spinForTimeoutThreshold)
2078                     LockSupport.parkNanos(this, nanosTimeout);
2079                 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2080                     break;
2081                 nanosTimeout = deadline - System.nanoTime();
2082             }
2083             if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2084                 interruptMode = REINTERRUPT;
2085             if (node.nextWaiter != null)
2086                 unlinkCancelledWaiters();
2087             if (interruptMode != 0)
2088                 reportInterruptAfterWait(interruptMode);
2089             return deadline - System.nanoTime();
2090         }
2091 
2092         /**
2093          * Implements absolute timed condition wait.
2094          * <ol>
2095          * <li> If current thread is interrupted, throw InterruptedException.
2096          * <li> Save lock state returned by {@link #getState}.
2097          * <li> Invoke {@link #release} with saved state as argument,
2098          *      throwing IllegalMonitorStateException if it fails.
2099          * <li> Block until signalled, interrupted, or timed out.
2100          * <li> Reacquire by invoking specialized version of
2101          *      {@link #acquire} with saved state as argument.
2102          * <li> If interrupted while blocked in step 4, throw InterruptedException.
2103          * <li> If timed out while blocked in step 4, return false, else true.
2104          * </ol>
2105          */
2106         public final boolean awaitUntil(Date deadline)
2107                 throws InterruptedException {
2108             long abstime = deadline.getTime();
2109             if (Thread.interrupted())
2110                 throw new InterruptedException();
2111             Node node = addConditionWaiter();
2112             int savedState = fullyRelease(node);
2113             boolean timedout = false;
2114             int interruptMode = 0;
2115             while (!isOnSyncQueue(node)) {
2116                 if (System.currentTimeMillis() > abstime) {
2117                     timedout = transferAfterCancelledWait(node);
2118                     break;
2119                 }
2120                 LockSupport.parkUntil(this, abstime);
2121                 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2122                     break;
2123             }
2124             if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2125                 interruptMode = REINTERRUPT;
2126             if (node.nextWaiter != null)
2127                 unlinkCancelledWaiters();
2128             if (interruptMode != 0)
2129                 reportInterruptAfterWait(interruptMode);
2130             return !timedout;
2131         }
2132 
2133         /**
2134          * Implements timed condition wait.
2135          * <ol>
2136          * <li> If current thread is interrupted, throw InterruptedException.
2137          * <li> Save lock state returned by {@link #getState}.
2138          * <li> Invoke {@link #release} with saved state as argument,
2139          *      throwing IllegalMonitorStateException if it fails.
2140          * <li> Block until signalled, interrupted, or timed out.
2141          * <li> Reacquire by invoking specialized version of
2142          *      {@link #acquire} with saved state as argument.
2143          * <li> If interrupted while blocked in step 4, throw InterruptedException.
2144          * <li> If timed out while blocked in step 4, return false, else true.
2145          * </ol>
2146          */
2147         public final boolean await(long time, TimeUnit unit)
2148                 throws InterruptedException {
2149             long nanosTimeout = unit.toNanos(time);
2150             if (Thread.interrupted())
2151                 throw new InterruptedException();
2152             Node node = addConditionWaiter();
2153             int savedState = fullyRelease(node);
2154             final long deadline = System.nanoTime() + nanosTimeout;
2155             boolean timedout = false;
2156             int interruptMode = 0;
2157             while (!isOnSyncQueue(node)) {
2158                 if (nanosTimeout <= 0L) {
2159                     timedout = transferAfterCancelledWait(node);
2160                     break;
2161                 }
2162                 if (nanosTimeout >= spinForTimeoutThreshold)
2163                     LockSupport.parkNanos(this, nanosTimeout);
2164                 if ((interruptMode = checkInterruptWhileWaiting(node)) != 0)
2165                     break;
2166                 nanosTimeout = deadline - System.nanoTime();
2167             }
2168             if (acquireQueued(node, savedState) && interruptMode != THROW_IE)
2169                 interruptMode = REINTERRUPT;
2170             if (node.nextWaiter != null)
2171                 unlinkCancelledWaiters();
2172             if (interruptMode != 0)
2173                 reportInterruptAfterWait(interruptMode);
2174             return !timedout;
2175         }
2176 
2177         //  support for instrumentation
2178 
2179         /**
2180          * Returns true if this condition was created by the given
2181          * synchronization object.
2182          *
2183          * @return {@code true} if owned
2184          */
2185         final boolean isOwnedBy(AbstractQueuedSynchronizer sync) {
2186             return sync == AbstractQueuedSynchronizer.this;
2187         }
2188 
2189         /**
2190          * Queries whether any threads are waiting on this condition.
2191          * Implements {@link AbstractQueuedSynchronizer#hasWaiters(ConditionObject)}.
2192          *
2193          * @return {@code true} if there are any waiting threads
2194          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2195          *         returns {@code false}
2196          */
2197         protected final boolean hasWaiters() {
2198             if (!isHeldExclusively())
2199                 throw new IllegalMonitorStateException();
2200             for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2201                 if (w.waitStatus == Node.CONDITION)
2202                     return true;
2203             }
2204             return false;
2205         }
2206 
2207         /**
2208          * Returns an estimate of the number of threads waiting on
2209          * this condition.
2210          * Implements {@link AbstractQueuedSynchronizer#getWaitQueueLength(ConditionObject)}.
2211          *
2212          * @return the estimated number of waiting threads
2213          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2214          *         returns {@code false}
2215          */
2216         protected final int getWaitQueueLength() {
2217             if (!isHeldExclusively())
2218                 throw new IllegalMonitorStateException();
2219             int n = 0;
2220             for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2221                 if (w.waitStatus == Node.CONDITION)
2222                     ++n;
2223             }
2224             return n;
2225         }
2226 
2227         /**
2228          * Returns a collection containing those threads that may be
2229          * waiting on this Condition.
2230          * Implements {@link AbstractQueuedSynchronizer#getWaitingThreads(ConditionObject)}.
2231          *
2232          * @return the collection of threads
2233          * @throws IllegalMonitorStateException if {@link #isHeldExclusively}
2234          *         returns {@code false}
2235          */
2236         protected final Collection<Thread> getWaitingThreads() {
2237             if (!isHeldExclusively())
2238                 throw new IllegalMonitorStateException();
2239             ArrayList<Thread> list = new ArrayList<Thread>();
2240             for (Node w = firstWaiter; w != null; w = w.nextWaiter) {
2241                 if (w.waitStatus == Node.CONDITION) {
2242                     Thread t = w.thread;
2243                     if (t != null)
2244                         list.add(t);
2245                 }
2246             }
2247             return list;
2248         }
2249     }
2250 
2251     /**
2252      * Setup to support compareAndSet. We need to natively implement
2253      * this here: For the sake of permitting future enhancements, we
2254      * cannot explicitly subclass AtomicInteger, which would be
2255      * efficient and useful otherwise. So, as the lesser of evils, we
2256      * natively implement using hotspot intrinsics API. And while we
2257      * are at it, we do the same for other CASable fields (which could
2258      * otherwise be done with atomic field updaters).
2259      */
2260     private static final Unsafe unsafe = Unsafe.getUnsafe();
2261     private static final long stateOffset;
2262     private static final long headOffset;
2263     private static final long tailOffset;
2264     private static final long waitStatusOffset;
2265     private static final long nextOffset;
2266 
2267     static {
2268         try {
2269             stateOffset = unsafe.objectFieldOffset
2270                 (AbstractQueuedSynchronizer.class.getDeclaredField("state"));
2271             headOffset = unsafe.objectFieldOffset
2272                 (AbstractQueuedSynchronizer.class.getDeclaredField("head"));
2273             tailOffset = unsafe.objectFieldOffset
2274                 (AbstractQueuedSynchronizer.class.getDeclaredField("tail"));
2275             waitStatusOffset = unsafe.objectFieldOffset
2276                 (Node.class.getDeclaredField("waitStatus"));
2277             nextOffset = unsafe.objectFieldOffset
2278                 (Node.class.getDeclaredField("next"));
2279 
2280         } catch (Exception ex) { throw new Error(ex); }
2281     }
2282 
2283     /**
2284      * CAS head field. Used only by enq.
2285      */
2286     private final boolean compareAndSetHead(Node update) {
2287         return unsafe.compareAndSwapObject(this, headOffset, null, update);
2288     }
2289 
2290     /**
2291      * CAS tail field. Used only by enq.
2292      */
2293     private final boolean compareAndSetTail(Node expect, Node update) {
2294         return unsafe.compareAndSwapObject(this, tailOffset, expect, update);
2295     }
2296 
2297     /**
2298      * CAS waitStatus field of a node.
2299      */
2300     private static final boolean compareAndSetWaitStatus(Node node,
2301                                                          int expect,
2302                                                          int update) {
2303         return unsafe.compareAndSwapInt(node, waitStatusOffset,
2304                                         expect, update);
2305     }
2306 
2307     /**
2308      * CAS next field of a node.
2309      */
2310     private static final boolean compareAndSetNext(Node node,
2311                                                    Node expect,
2312                                                    Node update) {
2313         return unsafe.compareAndSwapObject(node, nextOffset, expect, update);
2314     }
2315 }
AbstractQueuedSynchronizer.java
public abstract class AbstractOwnableSynchronizer implements java.io.Serializable {

    /** Use serial ID even though all fields transient. */
    private static final long serialVersionUID = 3737899427754241961L;

    /**
     * Empty constructor for use by subclasses.
     */
    protected AbstractOwnableSynchronizer() { }

    /**
     * 持有锁的线程
     */
    private transient Thread exclusiveOwnerThread;

    /**
     * 设置锁持有者
     */
    protected final void setExclusiveOwnerThread(Thread thread) {
        exclusiveOwnerThread = thread;
    }

    /**
     * 获取锁持有者
     */
    protected final Thread getExclusiveOwnerThread() {
        return exclusiveOwnerThread;
    }
}
AbstractOwnableSynchronizer.java

 

lock获锁

 

 

一、总体思路
 
AQS未使用原生Synchronized机制支持,在获锁的过程必须自我实现获锁、释放锁、线程阻塞、线程唤醒等功能。利用CLH虚拟的双向队列结构,
在未获锁情况下线程封装为队列节点入列阻塞等待,释放锁时候唤醒等待节点。
  • CLH (Craig, Landin, and Hagersten)是一个虚拟的双向队列结构,AQS中只是保留了头部(head)和尾部(tail)
  /**
     * Head of the wait queue, lazily initialized.  Except for
     * initialization, it is modified only via method setHead.  Note:
     * If head exists, its waitStatus is guaranteed not to be
     * CANCELLED.
     */
    private transient volatile Node head;
    /**
     * Tail of the wait queue, lazily initialized.  Modified only via
     * method enq to add new wait node.
     */
    private transient volatile Node tail;
CLH头部和尾部节点
  •  CLH虚拟队列结构如下图

  • volatile修饰的整形变量state标识锁的状态:state可大于1,以此来实现锁可重入(即获锁的线程允许再次获锁)
   /**
     * 同步锁状态
     */
    private volatile int state;
    protected final int getState() {
        return state;
    }
    protected final void setState(int newState) {
        state = newState;
    }
    /**
     * cas原子性更新state
     */
    protected final boolean compareAndSetState(int expect, int update) {
        return unsafe.compareAndSwapInt(this, stateOffset, expect, update);
    }

 

二、源码分析
 
(1)、以ReentrantLock#lock方法获取锁为入口
 public void lock() {
    sync.lock();
 }

(2)、sync为内部变量,构造ReentrantLock时根据参数创建公平锁和非公平锁,空参构造默认创建非公平锁。

   /** Synchronizer providing all implementation mechanics */
    private final Sync sync; 
   /**
     * Creates an instance of {@code ReentrantLock}.
     * This is equivalent to using {@code ReentrantLock(false)}.
     */
    public ReentrantLock() {
        sync = new NonfairSync();
    }
    /**
     * Creates an instance of {@code ReentrantLock} with the
     * given fairness policy.
     *
     * @param fair {@code true} if this lock should use a fair ordering policy
     */
    public ReentrantLock(boolean fair) {
        sync = fair ? new FairSync() : new NonfairSync();
    }

 (3)、Sync抽象类继承自AbstractQueuedSynchronizer(AQS),NonFairSync和FairSync都继承自Sync实现非公平锁和公平锁机制。

  /**
    * Base of synchronization control for this lock. Subclassed
    * into fair and nonfair versions below. Uses AQS state to
    * represent the number of holds on the lock.
    */
    abstract static class Sync extends AbstractQueuedSynchronizer {
        final void lock() {
            acquire(1);
        }
        // ......
    }
   /**
     * Sync object for non-fair locks
     */
    static final class NonfairSync extends Sync {
       //......
    }
    /**
     * Sync object for fair locks
     */
    static final class FairSync extends Sync {
        // ......
    }

(4)、先以FairSync为例,FairSync最终将调用AbstractQueuedSynchronizer#acquire(int arg)获锁

(其中arg参数即为获取锁的数量,要完全释放锁则获取多少数量,释放锁时必须释放对应数量)

public final void acquire(int arg) {
        if (!tryAcquire(arg) &&
            acquireQueued(addWaiter(Node.EXCLUSIVE), arg))
            selfInterrupt();
}

依次分析核心方法:

  • tryAcquire(int arg):尝试获锁
  • addWaiter(Node node):节点进入CLH等待队列
  • acquireQueued(Node node, int arg):节点是否可以获锁,获取不到即阻塞等待
  • selfInterrupt():自我产生中断

 

(4.1)、tryAcquire实现在FairSync内部。

   /**
     * Sync object for fair locks
     */
    static final class FairSync extends Sync {
        private static final long serialVersionUID = -3000897897090466540L;

        final void lock() {
            acquire(1);
        }
        /**
         * Fair version of tryAcquire.  Don't grant access unless
         * recursive call or no waiters or is first.
         */
        protected final boolean tryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            // 获取锁状态 0表示锁无人占用
            int c = getState();
            if (c == 0) {
                // 此时无前继节点即代表当前节点在队列头部,则利用cas原子获锁
                if (!hasQueuedPredecessors() &&
                    compareAndSetState(0, acquires)) {
                    // 利用AbstractOwnableSynchronizer提供的基础支持,设置当前线程为锁拥有者
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            // 锁可重入:锁拥有者可多次获取锁
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0)
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
    }

(4.2)、再来看看实现 AbstractQueuedSynchronizer#addWaiter(Node node) 节点入列的过程:

  • CLH双向虚拟队列的节点Node类
static final class Node {
        /** 标识为分享模式 */
        static final Node SHARED = new Node();
        /** 标识为独占模式 */
        static final Node EXCLUSIVE = null;

        /** 节点状态 0不表示属于以下任务状态 */
        /** 表示当前节点已取消等待锁 */
        static final int CANCELLED =  1;
        /** 表示当前节点需要唤醒状态,同时"后继节点"需要被阻塞 */
        static final int SIGNAL    = -1;
        /** 表示当前节点在等待Condition唤醒 */
        static final int CONDITION = -2;
        /** 表示其它线程获取到“共享锁”,对应的waitStatus的值 */
        static final int PROPAGATE = -3;
        volatile int waitStatus;
        /**
         * 前继节点
         */
        volatile Node prev;
        /**
         * 后继节点
         */
        volatile Node next;
        /**
         * 节点所对应的线程
         */
        volatile Thread thread;
        /**
         * nextWaiter是“区别当前CLH队列是 ‘独占锁’队列 还是 ‘共享锁’队列 的标记”
         * 若nextWaiter=SHARED,则CLH队列是“共享锁”队列;
         * 若nextWaiter=EXCLUSIVE,(即nextWaiter=null),则CLH队列是“独占锁”队列。
         */
        Node nextWaiter;

        final boolean isShared() {
            return nextWaiter == SHARED;
        }
        final Node predecessor() throws NullPointerException {
            Node p = prev;
            if (p == null)
                throw new NullPointerException();
            else
                return p;
        }
        Node() {    // Used to establish initial head or SHARED marker
        }
        Node(Thread thread, Node mode) {     // Used by addWaiter
            this.nextWaiter = mode;
            this.thread = thread;
        }
        Node(Thread thread, int waitStatus) { // Used by Condition
            this.waitStatus = waitStatus;
            this.thread = thread;
        }
    }
  • 入列逻辑:如队列不存在则会初始化,否则直接加入队尾。
/**
     * Creates and enqueues node for current thread and given mode.
     *
     * @param mode Node.EXCLUSIVE for exclusive, Node.SHARED for shared
     * @return the new node
     */
    private Node addWaiter(Node mode) {
        // 根据mode判断队列模式的标志,
        Node node = new Node(Thread.currentThread(), mode);
        // Try the fast path of enq; backup to full enq on failure
        Node pred = tail;
        // 如果CLH队列非空,将节点插入队尾
        if (pred != null) {
            node.prev = pred;
            // cas实现原子更新
            if (compareAndSetTail(pred, node)) {
                pred.next = node;
                return node;
            }
        }
        // CLH队列为空将初始化队列
        enq(node);
        return node;
    }

    private Node enq(final Node node) {
        for (;;) {
            Node t = tail;
            if (t == null) { // Must initialize
                if (compareAndSetHead(new Node()))
                    tail = head;
            } else {
                node.prev = t;
                if (compareAndSetTail(t, node)) {
                    t.next = node;
                    return t;
                }
            }
        }
    }

(4.3)、AbstractQueuedSynchronizer#acquireQueued(final Node node, int arg) 节点尝试获锁,如获取不到即阻塞等待。等被唤醒的时,将会返回阻塞过程中是否曾被中断过的标记。

   /**
     * Acquires in exclusive uninterruptible mode for thread already in
     * queue. Used by condition wait methods as well as acquire.
     *
     * @param node the node
     * @param arg the acquire argument
     * @return {@code true} if interrupted while waiting
     */
    final boolean acquireQueued(final Node node, int arg) {
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                // 当前节点已入列, 根据公平锁的原则判断当前节点前继p是否与head相等。
                // 队列为带头双向链表:公平原则核心体现在”p == head“即代表node为第一个节点,具有获锁的权利,否则即使被唤醒也无权利获锁。
                final Node p = node.predecessor();
                if (p == head && tryAcquire(arg)) {
                    setHead(node);
                    p.next = null; // help GC
                    failed = false;
                    return interrupted;
                }
                // 获锁失败,判断当前节点是否需要被阻塞等待
                // 1、阻塞,即将会等待其他线程调用LockSupport#unpark 或者 收到线程中断 唤醒
                // 2、非阻塞,即再进入for死循环竞争锁
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
    
    private static boolean shouldParkAfterFailedAcquire(Node pred, Node node) {
        // "前继节点"状态为Node.SIGNAL返回true 即表示当前节点将会被阻塞等待,等待"前继节点"释放锁,调用LockSupport#unpark唤醒
        // 其余返回false
        int ws = pred.waitStatus;
        if (ws == Node.SIGNAL)
            return true;
        // 状态大于0即表示取消状态
        if (ws > 0) {
            /*
             * 从pred开始往前遍历,清除掉ws>0 即已经取消状态的节点
             */
            do {
                node.prev = pred = pred.prev;
            } while (pred.waitStatus > 0);
            pred.next = node;
        } else {
            /*
             * 如果前继节点为“0”或者“共享锁”状态,则设置前继节点为SIGNAL状态。
             * 此时需要调用者再次进入尝试,确认节点是否需要阻塞
             */
            compareAndSetWaitStatus(pred, ws, Node.SIGNAL);
        }
        return false;
    }

    private final boolean parkAndCheckInterrupt() {
        // 利用LockSupport辅助类将线程阻塞
        LockSupport.park(this);
        // 判断状态:是否被因产生中断被唤醒,还是被LockSupport#unpark唤醒
        return Thread.interrupted();
    }

补充:被LockSupport#park阻塞的线程在几种情况下会被唤醒返回,因何种情况唤醒不得而知需要自我识别:

  • 调用LockSupport#unpark唤醒
  • 调用Thread#interrupt唤醒
  • 调用者无理由返回唤醒

 

(4.4)、先看看AbstractQueuedSynchronizer#selfInterrupt()的代码实现

static void selfInterrupt() {
    // 当前线程自我产生中断标记
    Thread.currentThread().interrupt();
}

为什么会在acquireQueued返回的时候还要自我产生中断呢? 

  • 首先,由于parkAndCheckInterrupt方法为了识别线程由于何种原因导致线程唤醒(一般为前两种情况的判断),会调用Thread.interrupted()方法,清除中断标记并返回。
  • 其次,Thread.interrupted()清除了中断标记,将会导致后续线程操作无法识别到中断标记,所以在确定了被线程中断唤醒情况下,自己重新生成一个中断。

 

(5)、AQS acquire非公平锁分析

  • 非公平锁NonFairSync和公平锁FairSync不同之处:如果锁未被占用则立即获取锁,不管节点是否为CLH队列头部。
   /**
     * Sync object for non-fair locks
     */
    static final class NonfairSync extends Sync {
        private static final long serialVersionUID = 7316153563782823691L;
        /**
         * 1、如锁未被占用,立即获取锁
         * 2、获锁失败再次进入 AbstractQueuedSynchronizer#acquire方法
         */
        final void lock() {
            if (compareAndSetState(0, 1))
                setExclusiveOwnerThread(Thread.currentThread());
            else
                acquire(1);
        }
        protected final boolean tryAcquire(int acquires) {
            // 实现在Sync内部
            return nonfairTryAcquire(acquires);
        }
    }

由于在分析公平锁FairSync已经分析过acquire方法,这里不再赘述。

  • Sync#nonfairTryAcquire非公平锁实现:
abstract static class Sync extends AbstractQueuedSynchronizer {
        private static final long serialVersionUID = -5179523762034025860L;

        abstract void lock();
        /**
         * Performs non-fair tryLock.  tryAcquire is implemented in
         * subclasses, but both need nonfair try for trylock method.
         */
        final boolean nonfairTryAcquire(int acquires) {
            final Thread current = Thread.currentThread();
            // 非公平锁:如锁未被占用,立即获取锁 
            int c = getState();
            if (c == 0) {
                if (compareAndSetState(0, acquires)) {
                    setExclusiveOwnerThread(current);
                    return true;
                }
            }
            // 锁可重入
            else if (current == getExclusiveOwnerThread()) {
                int nextc = c + acquires;
                if (nextc < 0) // overflow
                    throw new Error("Maximum lock count exceeded");
                setState(nextc);
                return true;
            }
            return false;
        }
        // ********
}

 

 

release释放锁
 
 
  
 (1)、以ReentrantLock#unlock方法释放锁为入口。注意:独占锁释放线程必须为锁持有者,否则将抛出IllegalMonitorStateException异常
public void unlock() {
     sync.release(1);
}

 (2)、sync为内部变量,实际将调用AbstractQueuedSynchronizer#release释放锁

public final boolean release(int arg) {
        // 尝试释放锁
        if (tryRelease(arg)) {
            // 获取锁的节点必定为CLH头节点
            Node h = head;
            if (h != null && h.waitStatus != 0)
                // 唤醒其后继节点
                unparkSuccessor(h);
            return true;
        }
        return false;
}

将分为两个步骤:

  • tryRelease: 尝试释放锁
  • unparkSuccessor:唤醒CLH队列最靠近头节点的有效后继节点

(2.1)、Sync类方法tryRelease逻辑很明确,即 设置state状态、清除锁持有者线程为null

protected final boolean tryRelease(int releases) {
            int c = getState() - releases;
            if (Thread.currentThread() != getExclusiveOwnerThread())
                throw new IllegalMonitorStateException();
            boolean free = false;
            // 由于可重入功能,需要完全释放为0才实际释放锁
            if (c == 0) {
                free = true;
                setExclusiveOwnerThread(null);
            }
            setState(c);
            return free;      
}

(2.2)、AbstractQueuedSynchronizer#unparkSuccessor方法唤醒继节点,即最靠近头节点的有效后继节点

private void unparkSuccessor(Node node) {
        /*
         * 如果当前节点状态为负数(意味着可能会被再次唤醒),因而设置该状态为0
         * 节点状态修改可能失败或者被其他等待线程修改,但不影响逻辑。
         */
        int ws = node.waitStatus;
        if (ws < 0)
            compareAndSetWaitStatus(node, ws, 0);
         
        /*
         * 节点释放锁则唤醒队列的下一个节点, 即:
         * 1、下一个节点不为null 且 状态为非取消 即唤醒。
         * 2、上述对Node节点分析, 下一个节点waitStatus>0表示为取消状态,此时从末尾遍历至node节点,
         *    找到最后一个非取消状态节点并唤醒,否则不做任何操作。
         */
        Node s = node.next; 
        if (s == null || s.waitStatus > 0) {
            s = null;
            for (Node t = tail; t != null && t != node; t = t.prev)
                if (t.waitStatus <= 0)
                    s = t;
        }
        if (s != null)
            LockSupport.unpark(s.thread);
}

 公平锁 和 非公平锁释放锁逻辑一致,只需分析一个即可。

 

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!