ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.62
Committed: Sun Oct 21 06:14:12 2012 UTC (11 years, 7 months ago) by jsr166
Branch: MAIN
Changes since 1.61: +0 -2 lines
Log Message:
delete trailing empty lines of javadoc

File Contents

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