ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.59
Committed: Thu Jun 9 07:48:43 2011 UTC (12 years, 11 months ago) by jsr166
Branch: MAIN
Changes since 1.58: +2 -4 lines
Log Message:
consistent style for code snippets

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 dl 1.16 import java.util.*;
9 dl 1.5 import java.util.concurrent.locks.*;
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     * binary semaphore has the property (unlike many {@link 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     */
128 dl 1.16
129 dl 1.23 public class Semaphore implements java.io.Serializable {
130 dl 1.16 private static final long serialVersionUID = -3222578661600680210L;
131 dl 1.25 /** All mechanics via AbstractQueuedSynchronizer subclass */
132 dl 1.23 private final Sync sync;
133    
134 dl 1.25 /**
135 dl 1.34 * Synchronization implementation for semaphore. Uses AQS state
136     * to represent permits. Subclassed into fair and nonfair
137     * versions.
138 dl 1.25 */
139 dl 1.34 abstract static class Sync extends AbstractQueuedSynchronizer {
140 dl 1.46 private static final long serialVersionUID = 1192457210091910933L;
141    
142 dl 1.34 Sync(int permits) {
143 dl 1.29 setState(permits);
144 dl 1.23 }
145 jsr166 1.45
146 dl 1.34 final int getPermits() {
147 dl 1.29 return getState();
148     }
149    
150 dl 1.34 final int nonfairTryAcquireShared(int acquires) {
151 dl 1.23 for (;;) {
152 dl 1.29 int available = getState();
153 dl 1.23 int remaining = available - acquires;
154     if (remaining < 0 ||
155 dl 1.29 compareAndSetState(available, remaining))
156 dl 1.23 return remaining;
157     }
158     }
159 jsr166 1.45
160 dl 1.34 protected final boolean tryReleaseShared(int releases) {
161 dl 1.23 for (;;) {
162 jsr166 1.54 int current = getState();
163     int next = current + releases;
164     if (next < current) // overflow
165     throw new Error("Maximum permit count exceeded");
166     if (compareAndSetState(current, next))
167 dl 1.23 return true;
168     }
169     }
170 dl 1.29
171 dl 1.34 final void reducePermits(int reductions) {
172 dl 1.29 for (;;) {
173     int current = getState();
174     int next = current - reductions;
175 jsr166 1.54 if (next > current) // underflow
176     throw new Error("Permit count underflow");
177 dl 1.29 if (compareAndSetState(current, next))
178     return;
179     }
180     }
181 dl 1.31
182 dl 1.34 final int drainPermits() {
183 dl 1.31 for (;;) {
184     int current = getState();
185     if (current == 0 || compareAndSetState(current, 0))
186     return current;
187     }
188     }
189 dl 1.23 }
190 dl 1.16
191 tim 1.1 /**
192 dl 1.34 * NonFair version
193     */
194 jsr166 1.55 static final class NonfairSync extends Sync {
195 dl 1.46 private static final long serialVersionUID = -2694183684443567898L;
196    
197 dl 1.34 NonfairSync(int permits) {
198     super(permits);
199     }
200 jsr166 1.45
201 dl 1.34 protected int tryAcquireShared(int acquires) {
202     return nonfairTryAcquireShared(acquires);
203     }
204     }
205    
206     /**
207     * Fair version
208     */
209 jsr166 1.55 static final class FairSync extends Sync {
210 dl 1.46 private static final long serialVersionUID = 2014338818796000944L;
211    
212 dl 1.34 FairSync(int permits) {
213     super(permits);
214     }
215 jsr166 1.45
216 dl 1.34 protected int tryAcquireShared(int acquires) {
217     for (;;) {
218 jsr166 1.53 if (hasQueuedPredecessors())
219 dl 1.34 return -1;
220     int available = getState();
221     int remaining = available - acquires;
222     if (remaining < 0 ||
223     compareAndSetState(available, remaining))
224     return remaining;
225     }
226     }
227     }
228    
229     /**
230 jsr166 1.51 * Creates a {@code Semaphore} with the given number of
231 dl 1.36 * permits and nonfair fairness setting.
232 jsr166 1.51 *
233     * @param permits the initial number of permits available.
234     * This value may be negative, in which case releases
235     * must occur before any acquires will be granted.
236 dl 1.36 */
237 jsr166 1.45 public Semaphore(int permits) {
238 dl 1.36 sync = new NonfairSync(permits);
239     }
240    
241     /**
242 jsr166 1.51 * Creates a {@code Semaphore} with the given number of
243 dl 1.19 * permits and the given fairness setting.
244 jsr166 1.51 *
245     * @param permits the initial number of permits available.
246     * This value may be negative, in which case releases
247     * must occur before any acquires will be granted.
248     * @param fair {@code true} if this semaphore will guarantee
249     * first-in first-out granting of permits under contention,
250     * else {@code false}
251 tim 1.1 */
252 jsr166 1.45 public Semaphore(int permits, boolean fair) {
253 jsr166 1.56 sync = fair ? new FairSync(permits) : new NonfairSync(permits);
254 tim 1.1 }
255    
256     /**
257     * Acquires a permit from this semaphore, blocking until one is
258 jsr166 1.51 * available, or the thread is {@linkplain Thread#interrupt interrupted}.
259 tim 1.1 *
260     * <p>Acquires a permit, if one is available and returns immediately,
261     * reducing the number of available permits by one.
262 jsr166 1.51 *
263 tim 1.1 * <p>If no permit is available then the current thread becomes
264     * disabled for thread scheduling purposes and lies dormant until
265     * one of two things happens:
266     * <ul>
267     * <li>Some other thread invokes the {@link #release} method for this
268 dl 1.16 * semaphore and the current thread is next to be assigned a permit; or
269 jsr166 1.51 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
270     * the current thread.
271 tim 1.1 * </ul>
272     *
273     * <p>If the current thread:
274     * <ul>
275     * <li>has its interrupted status set on entry to this method; or
276 jsr166 1.51 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
277 tim 1.1 * for a permit,
278     * </ul>
279     * then {@link InterruptedException} is thrown and the current thread's
280     * interrupted status is cleared.
281     *
282     * @throws InterruptedException if the current thread is interrupted
283     */
284 dl 1.2 public void acquire() throws InterruptedException {
285 dl 1.23 sync.acquireSharedInterruptibly(1);
286 dl 1.2 }
287 tim 1.1
288     /**
289     * Acquires a permit from this semaphore, blocking until one is
290     * available.
291     *
292     * <p>Acquires a permit, if one is available and returns immediately,
293     * reducing the number of available permits by one.
294 jsr166 1.51 *
295 tim 1.1 * <p>If no permit is available then the current thread becomes
296     * disabled for thread scheduling purposes and lies dormant until
297     * some other thread invokes the {@link #release} method for this
298 dl 1.16 * semaphore and the current thread is next to be assigned a permit.
299 tim 1.1 *
300 jsr166 1.51 * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
301     * while waiting for a permit then it will continue to wait, but the
302     * time at which the thread is assigned a permit may change compared to
303     * the time it would have received the permit had no interruption
304     * occurred. When the thread does return from this method its interrupt
305     * status will be set.
306 tim 1.1 */
307 dl 1.2 public void acquireUninterruptibly() {
308 dl 1.39 sync.acquireShared(1);
309 dl 1.2 }
310 tim 1.1
311     /**
312 jsr166 1.45 * Acquires a permit from this semaphore, only if one is available at the
313 tim 1.1 * time of invocation.
314 jsr166 1.51 *
315 tim 1.1 * <p>Acquires a permit, if one is available and returns immediately,
316 jsr166 1.51 * with the value {@code true},
317 tim 1.1 * reducing the number of available permits by one.
318     *
319     * <p>If no permit is available then this method will return
320 jsr166 1.51 * immediately with the value {@code false}.
321 tim 1.1 *
322 dl 1.27 * <p>Even when this semaphore has been set to use a
323 jsr166 1.51 * fair ordering policy, a call to {@code tryAcquire()} <em>will</em>
324 dl 1.27 * immediately acquire a permit if one is available, whether or not
325 jsr166 1.45 * other threads are currently waiting.
326     * This &quot;barging&quot; behavior can be useful in certain
327 dl 1.27 * circumstances, even though it breaks fairness. If you want to honor
328 jsr166 1.45 * the fairness setting, then use
329 dl 1.27 * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) }
330     * which is almost equivalent (it also detects interruption).
331     *
332 jsr166 1.51 * @return {@code true} if a permit was acquired and {@code false}
333     * otherwise
334 tim 1.1 */
335     public boolean tryAcquire() {
336 dl 1.34 return sync.nonfairTryAcquireShared(1) >= 0;
337 tim 1.1 }
338    
339     /**
340 jsr166 1.45 * Acquires a permit from this semaphore, if one becomes available
341 jsr166 1.51 * within the given waiting time and the current thread has not
342     * been {@linkplain Thread#interrupt interrupted}.
343     *
344 tim 1.1 * <p>Acquires a permit, if one is available and returns immediately,
345 jsr166 1.51 * with the value {@code true},
346 tim 1.1 * reducing the number of available permits by one.
347 jsr166 1.51 *
348     * <p>If no permit is available then the current thread becomes
349     * disabled for thread scheduling purposes and lies dormant until
350     * one of three things happens:
351 tim 1.1 * <ul>
352     * <li>Some other thread invokes the {@link #release} method for this
353 dl 1.16 * semaphore and the current thread is next to be assigned a permit; or
354 jsr166 1.51 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
355     * the current thread; or
356 tim 1.1 * <li>The specified waiting time elapses.
357     * </ul>
358 jsr166 1.51 *
359     * <p>If a permit is acquired then the value {@code true} is returned.
360     *
361 tim 1.1 * <p>If the current thread:
362     * <ul>
363     * <li>has its interrupted status set on entry to this method; or
364 jsr166 1.51 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
365     * to acquire a permit,
366 tim 1.1 * </ul>
367     * then {@link InterruptedException} is thrown and the current thread's
368     * interrupted status is cleared.
369 jsr166 1.51 *
370     * <p>If the specified waiting time elapses then the value {@code false}
371     * is returned. If the time is less than or equal to zero, the method
372     * will not wait at all.
373 tim 1.1 *
374     * @param timeout the maximum time to wait for a permit
375 jsr166 1.51 * @param unit the time unit of the {@code timeout} argument
376     * @return {@code true} if a permit was acquired and {@code false}
377     * if the waiting time elapsed before a permit was acquired
378 tim 1.1 * @throws InterruptedException if the current thread is interrupted
379     */
380 jsr166 1.45 public boolean tryAcquire(long timeout, TimeUnit unit)
381 tim 1.1 throws InterruptedException {
382 dl 1.39 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
383 tim 1.1 }
384    
385     /**
386     * Releases a permit, returning it to the semaphore.
387 jsr166 1.51 *
388     * <p>Releases a permit, increasing the number of available permits by
389     * one. If any threads are trying to acquire a permit, then one is
390     * selected and given the permit that was just released. That thread
391     * is (re)enabled for thread scheduling purposes.
392     *
393 tim 1.1 * <p>There is no requirement that a thread that releases a permit must
394     * have acquired that permit by calling {@link #acquire}.
395     * Correct usage of a semaphore is established by programming convention
396     * in the application.
397     */
398 dl 1.2 public void release() {
399 dl 1.23 sync.releaseShared(1);
400 dl 1.16 }
401 jsr166 1.45
402 dl 1.16 /**
403 jsr166 1.45 * Acquires the given number of permits from this semaphore,
404     * blocking until all are available,
405 jsr166 1.51 * or the thread is {@linkplain Thread#interrupt interrupted}.
406 dl 1.16 *
407     * <p>Acquires the given number of permits, if they are available,
408 jsr166 1.51 * and returns immediately, reducing the number of available permits
409     * by the given amount.
410 dl 1.16 *
411     * <p>If insufficient permits are available then the current thread becomes
412     * disabled for thread scheduling purposes and lies dormant until
413     * one of two things happens:
414     * <ul>
415 jsr166 1.45 * <li>Some other thread invokes one of the {@link #release() release}
416 dl 1.16 * methods for this semaphore, the current thread is next to be assigned
417     * permits and the number of available permits satisfies this request; or
418 jsr166 1.51 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
419     * the current thread.
420 dl 1.16 * </ul>
421     *
422     * <p>If the current thread:
423     * <ul>
424     * <li>has its interrupted status set on entry to this method; or
425 jsr166 1.51 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
426 dl 1.16 * for a permit,
427     * </ul>
428     * then {@link InterruptedException} is thrown and the current thread's
429 jsr166 1.45 * interrupted status is cleared.
430     * Any permits that were to be assigned to this thread are instead
431 dl 1.43 * assigned to other threads trying to acquire permits, as if
432     * permits had been made available by a call to {@link #release()}.
433 dl 1.16 *
434     * @param permits the number of permits to acquire
435     * @throws InterruptedException if the current thread is interrupted
436 jsr166 1.51 * @throws IllegalArgumentException if {@code permits} is negative
437 dl 1.16 */
438     public void acquire(int permits) throws InterruptedException {
439     if (permits < 0) throw new IllegalArgumentException();
440 dl 1.23 sync.acquireSharedInterruptibly(permits);
441 dl 1.16 }
442    
443     /**
444 jsr166 1.45 * Acquires the given number of permits from this semaphore,
445 dl 1.16 * blocking until all are available.
446     *
447     * <p>Acquires the given number of permits, if they are available,
448 jsr166 1.51 * and returns immediately, reducing the number of available permits
449     * by the given amount.
450 dl 1.16 *
451     * <p>If insufficient permits are available then the current thread becomes
452     * disabled for thread scheduling purposes and lies dormant until
453 jsr166 1.45 * some other thread invokes one of the {@link #release() release}
454 dl 1.16 * methods for this semaphore, the current thread is next to be assigned
455     * permits and the number of available permits satisfies this request.
456     *
457 jsr166 1.51 * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
458     * while waiting for permits then it will continue to wait and its
459     * position in the queue is not affected. When the thread does return
460     * from this method its interrupt status will be set.
461 dl 1.16 *
462     * @param permits the number of permits to acquire
463 jsr166 1.51 * @throws IllegalArgumentException if {@code permits} is negative
464 dl 1.16 *
465     */
466     public void acquireUninterruptibly(int permits) {
467     if (permits < 0) throw new IllegalArgumentException();
468 dl 1.39 sync.acquireShared(permits);
469 dl 1.16 }
470    
471     /**
472 dl 1.40 * Acquires the given number of permits from this semaphore, only
473     * if all are available at the time of invocation.
474 dl 1.41 *
475 jsr166 1.45 * <p>Acquires the given number of permits, if they are available, and
476 jsr166 1.51 * returns immediately, with the value {@code true},
477 dl 1.16 * reducing the number of available permits by the given amount.
478     *
479     * <p>If insufficient permits are available then this method will return
480 jsr166 1.51 * immediately with the value {@code false} and the number of available
481 dl 1.16 * permits is unchanged.
482     *
483 dl 1.27 * <p>Even when this semaphore has been set to use a fair ordering
484 jsr166 1.51 * policy, a call to {@code tryAcquire} <em>will</em>
485 dl 1.27 * immediately acquire a permit if one is available, whether or
486     * not other threads are currently waiting. This
487     * &quot;barging&quot; behavior can be useful in certain
488     * circumstances, even though it breaks fairness. If you want to
489     * honor the fairness setting, then use {@link #tryAcquire(int,
490     * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) }
491     * which is almost equivalent (it also detects interruption).
492     *
493 dl 1.16 * @param permits the number of permits to acquire
494 jsr166 1.51 * @return {@code true} if the permits were acquired and
495     * {@code false} otherwise
496     * @throws IllegalArgumentException if {@code permits} is negative
497 dl 1.16 */
498     public boolean tryAcquire(int permits) {
499     if (permits < 0) throw new IllegalArgumentException();
500 dl 1.34 return sync.nonfairTryAcquireShared(permits) >= 0;
501 dl 1.16 }
502    
503     /**
504 jsr166 1.45 * Acquires the given number of permits from this semaphore, if all
505 jsr166 1.51 * become available within the given waiting time and the current
506     * thread has not been {@linkplain Thread#interrupt interrupted}.
507     *
508 jsr166 1.45 * <p>Acquires the given number of permits, if they are available and
509 jsr166 1.51 * returns immediately, with the value {@code true},
510 dl 1.16 * reducing the number of available permits by the given amount.
511 jsr166 1.51 *
512 dl 1.16 * <p>If insufficient permits are available then
513     * the current thread becomes disabled for thread scheduling
514     * purposes and lies dormant until one of three things happens:
515     * <ul>
516 jsr166 1.45 * <li>Some other thread invokes one of the {@link #release() release}
517 dl 1.16 * methods for this semaphore, the current thread is next to be assigned
518     * permits and the number of available permits satisfies this request; or
519 jsr166 1.51 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
520     * the current thread; or
521 dl 1.16 * <li>The specified waiting time elapses.
522     * </ul>
523 jsr166 1.51 *
524     * <p>If the permits are acquired then the value {@code true} is returned.
525     *
526 dl 1.16 * <p>If the current thread:
527     * <ul>
528     * <li>has its interrupted status set on entry to this method; or
529 jsr166 1.51 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
530     * to acquire the permits,
531 dl 1.16 * </ul>
532     * then {@link InterruptedException} is thrown and the current thread's
533     * interrupted status is cleared.
534 jsr166 1.45 * Any permits that were to be assigned to this thread, are instead
535 dl 1.43 * assigned to other threads trying to acquire permits, as if
536     * the permits had been made available by a call to {@link #release()}.
537 dl 1.16 *
538 jsr166 1.51 * <p>If the specified waiting time elapses then the value {@code false}
539     * is returned. If the time is less than or equal to zero, the method
540     * will not wait at all. Any permits that were to be assigned to this
541     * thread, are instead assigned to other threads trying to acquire
542     * permits, as if the permits had been made available by a call to
543     * {@link #release()}.
544 dl 1.16 *
545     * @param permits the number of permits to acquire
546     * @param timeout the maximum time to wait for the permits
547 jsr166 1.51 * @param unit the time unit of the {@code timeout} argument
548     * @return {@code true} if all permits were acquired and {@code false}
549     * if the waiting time elapsed before all permits were acquired
550 dl 1.16 * @throws InterruptedException if the current thread is interrupted
551 jsr166 1.51 * @throws IllegalArgumentException if {@code permits} is negative
552 dl 1.16 */
553     public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
554     throws InterruptedException {
555     if (permits < 0) throw new IllegalArgumentException();
556 dl 1.39 return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
557 dl 1.16 }
558    
559     /**
560     * Releases the given number of permits, returning them to the semaphore.
561 jsr166 1.51 *
562 jsr166 1.45 * <p>Releases the given number of permits, increasing the number of
563 dl 1.16 * available permits by that amount.
564 dl 1.43 * If any threads are trying to acquire permits, then one
565 dl 1.16 * is selected and given the permits that were just released.
566     * If the number of available permits satisfies that thread's request
567 dl 1.43 * then that thread is (re)enabled for thread scheduling purposes;
568     * otherwise the thread will wait until sufficient permits are available.
569     * If there are still permits available
570     * after this thread's request has been satisfied, then those permits
571     * are assigned in turn to other threads trying to acquire permits.
572 dl 1.16 *
573     * <p>There is no requirement that a thread that releases a permit must
574     * have acquired that permit by calling {@link Semaphore#acquire acquire}.
575     * Correct usage of a semaphore is established by programming convention
576     * in the application.
577     *
578     * @param permits the number of permits to release
579 jsr166 1.51 * @throws IllegalArgumentException if {@code permits} is negative
580 dl 1.16 */
581     public void release(int permits) {
582     if (permits < 0) throw new IllegalArgumentException();
583 dl 1.23 sync.releaseShared(permits);
584 dl 1.2 }
585 tim 1.1
586     /**
587 dl 1.41 * Returns the current number of permits available in this semaphore.
588 jsr166 1.51 *
589 tim 1.1 * <p>This method is typically used for debugging and testing purposes.
590 jsr166 1.51 *
591     * @return the number of permits available in this semaphore
592 tim 1.1 */
593 dl 1.16 public int availablePermits() {
594 dl 1.29 return sync.getPermits();
595 tim 1.1 }
596 dl 1.15
597     /**
598 jsr166 1.45 * Acquires and returns all permits that are immediately available.
599 jsr166 1.51 *
600     * @return the number of permits acquired
601 dl 1.31 */
602     public int drainPermits() {
603     return sync.drainPermits();
604     }
605    
606     /**
607 dl 1.41 * Shrinks the number of available permits by the indicated
608 dl 1.40 * reduction. This method can be useful in subclasses that use
609     * semaphores to track resources that become unavailable. This
610 jsr166 1.51 * method differs from {@code acquire} in that it does not block
611 dl 1.40 * waiting for permits to become available.
612 jsr166 1.51 *
613 dl 1.15 * @param reduction the number of permits to remove
614 jsr166 1.51 * @throws IllegalArgumentException if {@code reduction} is negative
615 dl 1.15 */
616 dl 1.16 protected void reducePermits(int reduction) {
617 jsr166 1.53 if (reduction < 0) throw new IllegalArgumentException();
618 dl 1.29 sync.reducePermits(reduction);
619 dl 1.16 }
620    
621     /**
622 jsr166 1.51 * Returns {@code true} if this semaphore has fairness set true.
623     *
624     * @return {@code true} if this semaphore has fairness set true
625 dl 1.16 */
626     public boolean isFair() {
627 dl 1.34 return sync instanceof FairSync;
628 dl 1.22 }
629    
630     /**
631 dl 1.23 * Queries whether any threads are waiting to acquire. Note that
632 jsr166 1.51 * because cancellations may occur at any time, a {@code true}
633 dl 1.23 * return does not guarantee that any other thread will ever
634     * acquire. This method is designed primarily for use in
635     * monitoring of the system state.
636     *
637 jsr166 1.51 * @return {@code true} if there may be other threads waiting to
638     * acquire the lock
639 dl 1.22 */
640 jsr166 1.45 public final boolean hasQueuedThreads() {
641 dl 1.25 return sync.hasQueuedThreads();
642 dl 1.22 }
643    
644     /**
645 jsr166 1.51 * Returns an estimate of the number of threads waiting to acquire.
646     * The value is only an estimate because the number of threads may
647     * change dynamically while this method traverses internal data
648     * structures. This method is designed for use in monitoring of the
649     * system state, not for synchronization control.
650     *
651 dl 1.23 * @return the estimated number of threads waiting for this lock
652 dl 1.22 */
653 dl 1.23 public final int getQueueLength() {
654     return sync.getQueueLength();
655 dl 1.22 }
656    
657     /**
658 jsr166 1.51 * Returns a collection containing threads that may be waiting to acquire.
659     * Because the actual set of threads may change dynamically while
660     * constructing this result, the returned collection is only a best-effort
661     * estimate. The elements of the returned collection are in no particular
662     * order. This method is designed to facilitate construction of
663     * subclasses that provide more extensive monitoring facilities.
664     *
665 dl 1.23 * @return the collection of threads
666 dl 1.22 */
667 dl 1.23 protected Collection<Thread> getQueuedThreads() {
668     return sync.getQueuedThreads();
669 dl 1.16 }
670 dl 1.37
671     /**
672 dl 1.40 * Returns a string identifying this semaphore, as well as its state.
673 jsr166 1.51 * The state, in brackets, includes the String {@code "Permits ="}
674     * followed by the number of permits.
675     *
676     * @return a string identifying this semaphore, as well as its state
677 dl 1.37 */
678     public String toString() {
679     return super.toString() + "[Permits = " + sync.getPermits() + "]";
680     }
681 tim 1.1 }