View Javadoc
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;
37  import java.util.Collection;
38  import java.util.concurrent.locks.AbstractQueuedSynchronizer;
39  
40  /**
41   * A counting semaphore.  Conceptually, a semaphore maintains a set of
42   * permits.  Each {@link #acquire} blocks if necessary until a permit is
43   * available, and then takes it.  Each {@link #release} adds a permit,
44   * potentially releasing a blocking acquirer.
45   * However, no actual permit objects are used; the {@code Semaphore} just
46   * keeps a count of the number available and acts accordingly.
47   *
48   * <p>Semaphores are often used to restrict the number of threads than can
49   * access some (physical or logical) resource. For example, here is
50   * a class that uses a semaphore to control access to a pool of items:
51   *  <pre> {@code
52   * class Pool {
53   *   private static final int MAX_AVAILABLE = 100;
54   *   private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
55   *
56   *   public Object getItem() throws InterruptedException {
57   *     available.acquire();
58   *     return getNextAvailableItem();
59   *   }
60   *
61   *   public void putItem(Object x) {
62   *     if (markAsUnused(x))
63   *       available.release();
64   *   }
65   *
66   *   // Not a particularly efficient data structure; just for demo
67   *
68   *   protected Object[] items = ... whatever kinds of items being managed
69   *   protected boolean[] used = new boolean[MAX_AVAILABLE];
70   *
71   *   protected synchronized Object getNextAvailableItem() {
72   *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
73   *       if (!used[i]) {
74   *          used[i] = true;
75   *          return items[i];
76   *       }
77   *     }
78   *     return null; // not reached
79   *   }
80   *
81   *   protected synchronized boolean markAsUnused(Object item) {
82   *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
83   *       if (item == items[i]) {
84   *          if (used[i]) {
85   *            used[i] = false;
86   *            return true;
87   *          } else
88   *            return false;
89   *       }
90   *     }
91   *     return false;
92   *   }
93   * }}</pre>
94   *
95   * <p>Before obtaining an item each thread must acquire a permit from
96   * the semaphore, guaranteeing that an item is available for use. When
97   * the thread has finished with the item it is returned back to the
98   * pool and a permit is returned to the semaphore, allowing another
99   * thread to acquire that item.  Note that no synchronization lock is
100  * held when {@link #acquire} is called as that would prevent an item
101  * from being returned to the pool.  The semaphore encapsulates the
102  * synchronization needed to restrict access to the pool, separately
103  * from any synchronization needed to maintain the consistency of the
104  * pool itself.
105  *
106  * <p>A semaphore initialized to one, and which is used such that it
107  * only has at most one permit available, can serve as a mutual
108  * exclusion lock.  This is more commonly known as a <em>binary
109  * semaphore</em>, because it only has two states: one permit
110  * available, or zero permits available.  When used in this way, the
111  * binary semaphore has the property (unlike many {@link java.util.concurrent.locks.Lock}
112  * implementations), that the &quot;lock&quot; can be released by a
113  * thread other than the owner (as semaphores have no notion of
114  * ownership).  This can be useful in some specialized contexts, such
115  * as deadlock recovery.
116  *
117  * <p> The constructor for this class optionally accepts a
118  * <em>fairness</em> parameter. When set false, this class makes no
119  * guarantees about the order in which threads acquire permits. In
120  * particular, <em>barging</em> is permitted, that is, a thread
121  * invoking {@link #acquire} can be allocated a permit ahead of a
122  * thread that has been waiting - logically the new thread places itself at
123  * the head of the queue of waiting threads. When fairness is set true, the
124  * semaphore guarantees that threads invoking any of the {@link
125  * #acquire() acquire} methods are selected to obtain permits in the order in
126  * which their invocation of those methods was processed
127  * (first-in-first-out; FIFO). Note that FIFO ordering necessarily
128  * applies to specific internal points of execution within these
129  * methods.  So, it is possible for one thread to invoke
130  * {@code acquire} before another, but reach the ordering point after
131  * the other, and similarly upon return from the method.
132  * Also note that the untimed {@link #tryAcquire() tryAcquire} methods do not
133  * honor the fairness setting, but will take any permits that are
134  * available.
135  *
136  * <p>Generally, semaphores used to control resource access should be
137  * initialized as fair, to ensure that no thread is starved out from
138  * accessing a resource. When using semaphores for other kinds of
139  * synchronization control, the throughput advantages of non-fair
140  * ordering often outweigh fairness considerations.
141  *
142  * <p>This class also provides convenience methods to {@link
143  * #acquire(int) acquire} and {@link #release(int) release} multiple
144  * permits at a time.  Beware of the increased risk of indefinite
145  * postponement when these methods are used without fairness set true.
146  *
147  * <p>Memory consistency effects: Actions in a thread prior to calling
148  * a "release" method such as {@code release()}
149  * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
150  * actions following a successful "acquire" method such as {@code acquire()}
151  * in another thread.
152  *
153  * @since 1.5
154  * @author Doug Lea
155  */
156 public class Semaphore implements java.io.Serializable {
157     private static final long serialVersionUID = -3222578661600680210L;
158     /** All mechanics via AbstractQueuedSynchronizer subclass */
159     private final Sync sync;
160 
161     /**
162      * Synchronization implementation for semaphore.  Uses AQS state
163      * to represent permits. Subclassed into fair and nonfair
164      * versions.
165      */
166     abstract static class Sync extends AbstractQueuedSynchronizer {
167         private static final long serialVersionUID = 1192457210091910933L;
168 
169         Sync(int permits) {
170             setState(permits);
171         }
172 
173         final int getPermits() {
174             return getState();
175         }
176 
177         final int nonfairTryAcquireShared(int acquires) {
178             for (;;) {
179                 int available = getState();
180                 int remaining = available - acquires;
181                 if (remaining < 0 ||
182                     compareAndSetState(available, remaining))
183                     return remaining;
184             }
185         }
186 
187         protected final boolean tryReleaseShared(int releases) {
188             for (;;) {
189                 int current = getState();
190                 int next = current + releases;
191                 if (next < current) // overflow
192                     throw new Error("Maximum permit count exceeded");
193                 if (compareAndSetState(current, next))
194                     return true;
195             }
196         }
197 
198         final void reducePermits(int reductions) {
199             for (;;) {
200                 int current = getState();
201                 int next = current - reductions;
202                 if (next > current) // underflow
203                     throw new Error("Permit count underflow");
204                 if (compareAndSetState(current, next))
205                     return;
206             }
207         }
208 
209         final int drainPermits() {
210             for (;;) {
211                 int current = getState();
212                 if (current == 0 || compareAndSetState(current, 0))
213                     return current;
214             }
215         }
216     }
217 
218     /**
219      * NonFair version
220      */
221     static final class NonfairSync extends Sync {
222         private static final long serialVersionUID = -2694183684443567898L;
223 
224         NonfairSync(int permits) {
225             super(permits);
226         }
227 
228         protected int tryAcquireShared(int acquires) {
229             return nonfairTryAcquireShared(acquires);
230         }
231     }
232 
233     /**
234      * Fair version
235      */
236     static final class FairSync extends Sync {
237         private static final long serialVersionUID = 2014338818796000944L;
238 
239         FairSync(int permits) {
240             super(permits);
241         }
242 
243         protected int tryAcquireShared(int acquires) {
244             for (;;) {
245                 if (hasQueuedPredecessors())
246                     return -1;
247                 int available = getState();
248                 int remaining = available - acquires;
249                 if (remaining < 0 ||
250                     compareAndSetState(available, remaining))
251                     return remaining;
252             }
253         }
254     }
255 
256     /**
257      * Creates a {@code Semaphore} with the given number of
258      * permits and nonfair fairness setting.
259      *
260      * @param permits the initial number of permits available.
261      *        This value may be negative, in which case releases
262      *        must occur before any acquires will be granted.
263      */
264     public Semaphore(int permits) {
265         sync = new NonfairSync(permits);
266     }
267 
268     /**
269      * Creates a {@code Semaphore} with the given number of
270      * permits and the given fairness setting.
271      *
272      * @param permits the initial number of permits available.
273      *        This value may be negative, in which case releases
274      *        must occur before any acquires will be granted.
275      * @param fair {@code true} if this semaphore will guarantee
276      *        first-in first-out granting of permits under contention,
277      *        else {@code false}
278      */
279     public Semaphore(int permits, boolean fair) {
280         sync = fair ? new FairSync(permits) : new NonfairSync(permits);
281     }
282 
283     /**
284      * Acquires a permit from this semaphore, blocking until one is
285      * available, or the thread is {@linkplain Thread#interrupt interrupted}.
286      *
287      * <p>Acquires a permit, if one is available and returns immediately,
288      * reducing the number of available permits by one.
289      *
290      * <p>If no permit is available then the current thread becomes
291      * disabled for thread scheduling purposes and lies dormant until
292      * one of two things happens:
293      * <ul>
294      * <li>Some other thread invokes the {@link #release} method for this
295      * semaphore and the current thread is next to be assigned a permit; or
296      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
297      * the current thread.
298      * </ul>
299      *
300      * <p>If the current thread:
301      * <ul>
302      * <li>has its interrupted status set on entry to this method; or
303      * <li>is {@linkplain Thread#interrupt interrupted} while waiting
304      * for a permit,
305      * </ul>
306      * then {@link InterruptedException} is thrown and the current thread's
307      * interrupted status is cleared.
308      *
309      * @throws InterruptedException if the current thread is interrupted
310      */
311     public void acquire() throws InterruptedException {
312         sync.acquireSharedInterruptibly(1);
313     }
314 
315     /**
316      * Acquires a permit from this semaphore, blocking until one is
317      * available.
318      *
319      * <p>Acquires a permit, if one is available and returns immediately,
320      * reducing the number of available permits by one.
321      *
322      * <p>If no permit is available then the current thread becomes
323      * disabled for thread scheduling purposes and lies dormant until
324      * some other thread invokes the {@link #release} method for this
325      * semaphore and the current thread is next to be assigned a permit.
326      *
327      * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
328      * while waiting for a permit then it will continue to wait, but the
329      * time at which the thread is assigned a permit may change compared to
330      * the time it would have received the permit had no interruption
331      * occurred.  When the thread does return from this method its interrupt
332      * status will be set.
333      */
334     public void acquireUninterruptibly() {
335         sync.acquireShared(1);
336     }
337 
338     /**
339      * Acquires a permit from this semaphore, only if one is available at the
340      * time of invocation.
341      *
342      * <p>Acquires a permit, if one is available and returns immediately,
343      * with the value {@code true},
344      * reducing the number of available permits by one.
345      *
346      * <p>If no permit is available then this method will return
347      * immediately with the value {@code false}.
348      *
349      * <p>Even when this semaphore has been set to use a
350      * fair ordering policy, a call to {@code tryAcquire()} <em>will</em>
351      * immediately acquire a permit if one is available, whether or not
352      * other threads are currently waiting.
353      * This &quot;barging&quot; behavior can be useful in certain
354      * circumstances, even though it breaks fairness. If you want to honor
355      * the fairness setting, then use
356      * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) }
357      * which is almost equivalent (it also detects interruption).
358      *
359      * @return {@code true} if a permit was acquired and {@code false}
360      *         otherwise
361      */
362     public boolean tryAcquire() {
363         return sync.nonfairTryAcquireShared(1) >= 0;
364     }
365 
366     /**
367      * Acquires a permit from this semaphore, if one becomes available
368      * within the given waiting time and the current thread has not
369      * been {@linkplain Thread#interrupt interrupted}.
370      *
371      * <p>Acquires a permit, if one is available and returns immediately,
372      * with the value {@code true},
373      * reducing the number of available permits by one.
374      *
375      * <p>If no permit is available then the current thread becomes
376      * disabled for thread scheduling purposes and lies dormant until
377      * one of three things happens:
378      * <ul>
379      * <li>Some other thread invokes the {@link #release} method for this
380      * semaphore and the current thread is next to be assigned a permit; or
381      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
382      * the current thread; or
383      * <li>The specified waiting time elapses.
384      * </ul>
385      *
386      * <p>If a permit is acquired then the value {@code true} is returned.
387      *
388      * <p>If the current thread:
389      * <ul>
390      * <li>has its interrupted status set on entry to this method; or
391      * <li>is {@linkplain Thread#interrupt interrupted} while waiting
392      * to acquire a permit,
393      * </ul>
394      * then {@link InterruptedException} is thrown and the current thread's
395      * interrupted status is cleared.
396      *
397      * <p>If the specified waiting time elapses then the value {@code false}
398      * is returned.  If the time is less than or equal to zero, the method
399      * will not wait at all.
400      *
401      * @param timeout the maximum time to wait for a permit
402      * @param unit the time unit of the {@code timeout} argument
403      * @return {@code true} if a permit was acquired and {@code false}
404      *         if the waiting time elapsed before a permit was acquired
405      * @throws InterruptedException if the current thread is interrupted
406      */
407     public boolean tryAcquire(long timeout, TimeUnit unit)
408         throws InterruptedException {
409         return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
410     }
411 
412     /**
413      * Releases a permit, returning it to the semaphore.
414      *
415      * <p>Releases a permit, increasing the number of available permits by
416      * one.  If any threads are trying to acquire a permit, then one is
417      * selected and given the permit that was just released.  That thread
418      * is (re)enabled for thread scheduling purposes.
419      *
420      * <p>There is no requirement that a thread that releases a permit must
421      * have acquired that permit by calling {@link #acquire}.
422      * Correct usage of a semaphore is established by programming convention
423      * in the application.
424      */
425     public void release() {
426         sync.releaseShared(1);
427     }
428 
429     /**
430      * Acquires the given number of permits from this semaphore,
431      * blocking until all are available,
432      * or the thread is {@linkplain Thread#interrupt interrupted}.
433      *
434      * <p>Acquires the given number of permits, if they are available,
435      * and returns immediately, reducing the number of available permits
436      * by the given amount.
437      *
438      * <p>If insufficient permits are available then the current thread becomes
439      * disabled for thread scheduling purposes and lies dormant until
440      * one of two things happens:
441      * <ul>
442      * <li>Some other thread invokes one of the {@link #release() release}
443      * methods for this semaphore, the current thread is next to be assigned
444      * permits and the number of available permits satisfies this request; or
445      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
446      * the current thread.
447      * </ul>
448      *
449      * <p>If the current thread:
450      * <ul>
451      * <li>has its interrupted status set on entry to this method; or
452      * <li>is {@linkplain Thread#interrupt interrupted} while waiting
453      * for a permit,
454      * </ul>
455      * then {@link InterruptedException} is thrown and the current thread's
456      * interrupted status is cleared.
457      * Any permits that were to be assigned to this thread are instead
458      * assigned to other threads trying to acquire permits, as if
459      * permits had been made available by a call to {@link #release()}.
460      *
461      * @param permits the number of permits to acquire
462      * @throws InterruptedException if the current thread is interrupted
463      * @throws IllegalArgumentException if {@code permits} is negative
464      */
465     public void acquire(int permits) throws InterruptedException {
466         if (permits < 0) throw new IllegalArgumentException();
467         sync.acquireSharedInterruptibly(permits);
468     }
469 
470     /**
471      * Acquires the given number of permits from this semaphore,
472      * blocking until all are available.
473      *
474      * <p>Acquires the given number of permits, if they are available,
475      * and returns immediately, reducing the number of available permits
476      * by the given amount.
477      *
478      * <p>If insufficient permits are available then the current thread becomes
479      * disabled for thread scheduling purposes and lies dormant until
480      * some other thread invokes one of the {@link #release() release}
481      * methods for this semaphore, the current thread is next to be assigned
482      * permits and the number of available permits satisfies this request.
483      *
484      * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
485      * while waiting for permits then it will continue to wait and its
486      * position in the queue is not affected.  When the thread does return
487      * from this method its interrupt status will be set.
488      *
489      * @param permits the number of permits to acquire
490      * @throws IllegalArgumentException if {@code permits} is negative
491      */
492     public void acquireUninterruptibly(int permits) {
493         if (permits < 0) throw new IllegalArgumentException();
494         sync.acquireShared(permits);
495     }
496 
497     /**
498      * Acquires the given number of permits from this semaphore, only
499      * if all are available at the time of invocation.
500      *
501      * <p>Acquires the given number of permits, if they are available, and
502      * returns immediately, with the value {@code true},
503      * reducing the number of available permits by the given amount.
504      *
505      * <p>If insufficient permits are available then this method will return
506      * immediately with the value {@code false} and the number of available
507      * permits is unchanged.
508      *
509      * <p>Even when this semaphore has been set to use a fair ordering
510      * policy, a call to {@code tryAcquire} <em>will</em>
511      * immediately acquire a permit if one is available, whether or
512      * not other threads are currently waiting.  This
513      * &quot;barging&quot; behavior can be useful in certain
514      * circumstances, even though it breaks fairness. If you want to
515      * honor the fairness setting, then use {@link #tryAcquire(int,
516      * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) }
517      * which is almost equivalent (it also detects interruption).
518      *
519      * @param permits the number of permits to acquire
520      * @return {@code true} if the permits were acquired and
521      *         {@code false} otherwise
522      * @throws IllegalArgumentException if {@code permits} is negative
523      */
524     public boolean tryAcquire(int permits) {
525         if (permits < 0) throw new IllegalArgumentException();
526         return sync.nonfairTryAcquireShared(permits) >= 0;
527     }
528 
529     /**
530      * Acquires the given number of permits from this semaphore, if all
531      * become available within the given waiting time and the current
532      * thread has not been {@linkplain Thread#interrupt interrupted}.
533      *
534      * <p>Acquires the given number of permits, if they are available and
535      * returns immediately, with the value {@code true},
536      * reducing the number of available permits by the given amount.
537      *
538      * <p>If insufficient permits are available then
539      * the current thread becomes disabled for thread scheduling
540      * purposes and lies dormant until one of three things happens:
541      * <ul>
542      * <li>Some other thread invokes one of the {@link #release() release}
543      * methods for this semaphore, the current thread is next to be assigned
544      * permits and the number of available permits satisfies this request; or
545      * <li>Some other thread {@linkplain Thread#interrupt interrupts}
546      * the current thread; or
547      * <li>The specified waiting time elapses.
548      * </ul>
549      *
550      * <p>If the permits are acquired then the value {@code true} is returned.
551      *
552      * <p>If the current thread:
553      * <ul>
554      * <li>has its interrupted status set on entry to this method; or
555      * <li>is {@linkplain Thread#interrupt interrupted} while waiting
556      * to acquire the permits,
557      * </ul>
558      * then {@link InterruptedException} is thrown and the current thread's
559      * interrupted status is cleared.
560      * Any permits that were to be assigned to this thread, are instead
561      * assigned to other threads trying to acquire permits, as if
562      * the permits had been made available by a call to {@link #release()}.
563      *
564      * <p>If the specified waiting time elapses then the value {@code false}
565      * is returned.  If the time is less than or equal to zero, the method
566      * will not wait at all.  Any permits that were to be assigned to this
567      * thread, are instead assigned to other threads trying to acquire
568      * permits, as if the permits had been made available by a call to
569      * {@link #release()}.
570      *
571      * @param permits the number of permits to acquire
572      * @param timeout the maximum time to wait for the permits
573      * @param unit the time unit of the {@code timeout} argument
574      * @return {@code true} if all permits were acquired and {@code false}
575      *         if the waiting time elapsed before all permits were acquired
576      * @throws InterruptedException if the current thread is interrupted
577      * @throws IllegalArgumentException if {@code permits} is negative
578      */
579     public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
580         throws InterruptedException {
581         if (permits < 0) throw new IllegalArgumentException();
582         return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
583     }
584 
585     /**
586      * Releases the given number of permits, returning them to the semaphore.
587      *
588      * <p>Releases the given number of permits, increasing the number of
589      * available permits by that amount.
590      * If any threads are trying to acquire permits, then one
591      * is selected and given the permits that were just released.
592      * If the number of available permits satisfies that thread's request
593      * then that thread is (re)enabled for thread scheduling purposes;
594      * otherwise the thread will wait until sufficient permits are available.
595      * If there are still permits available
596      * after this thread's request has been satisfied, then those permits
597      * are assigned in turn to other threads trying to acquire permits.
598      *
599      * <p>There is no requirement that a thread that releases a permit must
600      * have acquired that permit by calling {@link Semaphore#acquire acquire}.
601      * Correct usage of a semaphore is established by programming convention
602      * in the application.
603      *
604      * @param permits the number of permits to release
605      * @throws IllegalArgumentException if {@code permits} is negative
606      */
607     public void release(int permits) {
608         if (permits < 0) throw new IllegalArgumentException();
609         sync.releaseShared(permits);
610     }
611 
612     /**
613      * Returns the current number of permits available in this semaphore.
614      *
615      * <p>This method is typically used for debugging and testing purposes.
616      *
617      * @return the number of permits available in this semaphore
618      */
619     public int availablePermits() {
620         return sync.getPermits();
621     }
622 
623     /**
624      * Acquires and returns all permits that are immediately available.
625      *
626      * @return the number of permits acquired
627      */
628     public int drainPermits() {
629         return sync.drainPermits();
630     }
631 
632     /**
633      * Shrinks the number of available permits by the indicated
634      * reduction. This method can be useful in subclasses that use
635      * semaphores to track resources that become unavailable. This
636      * method differs from {@code acquire} in that it does not block
637      * waiting for permits to become available.
638      *
639      * @param reduction the number of permits to remove
640      * @throws IllegalArgumentException if {@code reduction} is negative
641      */
642     protected void reducePermits(int reduction) {
643         if (reduction < 0) throw new IllegalArgumentException();
644         sync.reducePermits(reduction);
645     }
646 
647     /**
648      * Returns {@code true} if this semaphore has fairness set true.
649      *
650      * @return {@code true} if this semaphore has fairness set true
651      */
652     public boolean isFair() {
653         return sync instanceof FairSync;
654     }
655 
656     /**
657      * Queries whether any threads are waiting to acquire. Note that
658      * because cancellations may occur at any time, a {@code true}
659      * return does not guarantee that any other thread will ever
660      * acquire.  This method is designed primarily for use in
661      * monitoring of the system state.
662      *
663      * @return {@code true} if there may be other threads waiting to
664      *         acquire the lock
665      */
666     public final boolean hasQueuedThreads() {
667         return sync.hasQueuedThreads();
668     }
669 
670     /**
671      * Returns an estimate of the number of threads waiting to acquire.
672      * The value is only an estimate because the number of threads may
673      * change dynamically while this method traverses internal data
674      * structures.  This method is designed for use in monitoring of the
675      * system state, not for synchronization control.
676      *
677      * @return the estimated number of threads waiting for this lock
678      */
679     public final int getQueueLength() {
680         return sync.getQueueLength();
681     }
682 
683     /**
684      * Returns a collection containing threads that may be waiting to acquire.
685      * Because the actual set of threads may change dynamically while
686      * constructing this result, the returned collection is only a best-effort
687      * estimate.  The elements of the returned collection are in no particular
688      * order.  This method is designed to facilitate construction of
689      * subclasses that provide more extensive monitoring facilities.
690      *
691      * @return the collection of threads
692      */
693     protected Collection<Thread> getQueuedThreads() {
694         return sync.getQueuedThreads();
695     }
696 
697     /**
698      * Returns a string identifying this semaphore, as well as its state.
699      * The state, in brackets, includes the String {@code "Permits ="}
700      * followed by the number of permits.
701      *
702      * @return a string identifying this semaphore, as well as its state
703      */
704     public String toString() {
705         return super.toString() + "[Permits = " + sync.getPermits() + "]";
706     }
707 }