ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.20
Committed: Tue Dec 23 19:38:09 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.19: +3 -1 lines
Log Message:
cache finals across volatiles; avoid readResolve; doc improvments; timed invokeAll interleaves

File Contents

# User Rev Content
1 dl 1.2 /*
2     * Written by Doug Lea with assistance from members of JCP JSR-166
3     * Expert Group and released to the public domain. Use, modify, and
4     * redistribute this code in any way without acknowledgement.
5     */
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 dl 1.16 import java.util.concurrent.atomic.*;
11 tim 1.1
12     /**
13     * A counting semaphore. Conceptually, a semaphore maintains a set of
14     * permits. Each {@link #acquire} blocks if necessary until a permit is
15     * available, and then takes it. Each {@link #release} adds a permit,
16     * potentially releasing a blocking acquirer.
17     * However, no actual permit objects are used; the <tt>Semaphore</tt> just
18     * keeps a count of the number available and acts accordingly.
19     *
20 dl 1.16 * <p>Semaphores are often used to restrict the number of threads than can
21 tim 1.1 * access some (physical or logical) resource. For example, here is
22     * a class that uses a semaphore to control access to a pool of items:
23     * <pre>
24     * class Pool {
25     * private static final MAX_AVAILABLE = 100;
26 dl 1.16 * private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
27 tim 1.1 *
28     * public Object getItem() throws InterruptedException {
29     * available.acquire();
30     * return getNextAvailableItem();
31     * }
32     *
33     * public void putItem(Object x) {
34     * if (markAsUnused(x))
35     * available.release();
36     * }
37     *
38     * // Not a particularly efficient data structure; just for demo
39     *
40     * protected Object[] items = ... whatever kinds of items being managed
41     * protected boolean[] used = new boolean[MAX_AVAILABLE];
42     *
43     * protected synchronized Object getNextAvailableItem() {
44     * for (int i = 0; i < MAX_AVAILABLE; ++i) {
45     * if (!used[i]) {
46     * used[i] = true;
47     * return items[i];
48     * }
49     * }
50     * return null; // not reached
51     * }
52     *
53     * protected synchronized boolean markAsUnused(Object item) {
54     * for (int i = 0; i < MAX_AVAILABLE; ++i) {
55     * if (item == items[i]) {
56     * if (used[i]) {
57     * used[i] = false;
58     * return true;
59 tim 1.8 * } else
60 tim 1.1 * return false;
61     * }
62     * }
63     * return false;
64     * }
65     *
66     * }
67     * </pre>
68     *
69 dl 1.16 * <p>Before obtaining an item each thread must acquire a permit from
70     * the semaphore, guaranteeing that an item is available for use. When
71     * the thread has finished with the item it is returned back to the
72     * pool and a permit is returned to the semaphore, allowing another
73     * thread to acquire that item. Note that no synchronization lock is
74     * held when {@link #acquire} is called as that would prevent an item
75     * from being returned to the pool. The semaphore encapsulates the
76     * synchronization needed to restrict access to the pool, separately
77     * from any synchronization needed to maintain the consistency of the
78     * pool itself.
79     *
80     * <p>A semaphore initialized to one, and which is used such that it
81     * only has at most one permit available, can serve as a mutual
82     * exclusion lock. This is more commonly known as a <em>binary
83     * semaphore</em>, because it only has two states: one permit
84     * available, or zero permits available. When used in this way, the
85     * binary semaphore has the property (unlike many {@link Lock}
86 dl 1.18 * implementations), that the &quot;lock&quot; can be released by a
87 dl 1.16 * thread other than the owner (as semaphores have no notion of
88     * ownership). This can be useful in some specialized contexts, such
89     * as deadlock recovery.
90     *
91     * <p> The constructor for this class accepts a <em>fairness</em>
92     * parameter. When set false, this class makes no guarantees about the
93 dl 1.19 * order in which threads acquire permits. In particular, <em>barging</em> is
94 dl 1.16 * permitted, that is, a thread invoking {@link #acquire} can be
95     * allocated a permit ahead of a thread that has been waiting. When
96     * fairness is set true, the semaphore guarantees that threads
97     * invoking any of the {@link #acquire() acquire} methods are
98     * allocated permits in the order in which their invocation of those
99     * methods was processed (first-in-first-out; FIFO). Note that FIFO
100     * ordering necessarily applies to specific internal points of
101     * execution within these methods. So, it is possible for one thread
102     * to invoke <tt>acquire</tt> before another, but reach the ordering
103     * point after the other, and similarly upon return from the method.
104     *
105     * <p>Generally, semaphores used to control resource access should be
106     * initialized as fair, to ensure that no thread is starved out from
107     * accessing a resource. When using semaphores for other kinds of
108     * synchronization control, the throughput advantages of non-fair
109     * ordering often outweigh fairness considerations.
110     *
111     * <p>This class also provides convenience methods to {@link
112     * #acquire(int) acquire} and {@link #release(int) release} multiple
113     * permits at a time. Beware of the increased risk of indefinite
114 dl 1.19 * postponement when these methods are used without fairness set true.
115 tim 1.1 *
116     * @since 1.5
117 dl 1.4 * @author Doug Lea
118 tim 1.1 *
119     */
120 dl 1.16
121 dl 1.2 public class Semaphore implements java.io.Serializable {
122 dl 1.16 /*
123     * The underlying algorithm here is a simplified adaptation of
124     * that used for ReentrantLock. See the internal documentation of
125 dl 1.20 * lock package classes for detailed explanation.
126 dl 1.16 */
127    
128     private static final long serialVersionUID = -3222578661600680210L;
129 dl 1.9
130 dl 1.16 /** Node status value to indicate thread has cancelled */
131     private static final int CANCELLED = 1;
132     /** Node status value to indicate successor needs unparking */
133     private static final int SIGNAL = -1;
134     /** Node class for waiting threads */
135     private static class Node {
136     volatile int status;
137     volatile Node prev;
138     volatile Node next;
139     Thread thread;
140     Node(Thread t) { thread = t; }
141     }
142 dl 1.2
143 dl 1.16 /** Number of available permits held in a separate AtomicInteger */
144     private final AtomicInteger perms;
145     /** Head of the wait queue, lazily initialized. */
146     private transient volatile Node head;
147     /** Tail of the wait queue, lazily initialized. */
148     private transient volatile Node tail;
149     /** true if barging disabled */
150     private final boolean fair;
151    
152     // Atomic update support
153    
154     private static final
155     AtomicReferenceFieldUpdater<Semaphore, Node> tailUpdater =
156     AtomicReferenceFieldUpdater.<Semaphore, Node>newUpdater
157     (Semaphore.class, Node.class, "tail");
158     private static final
159     AtomicReferenceFieldUpdater<Semaphore, Node> headUpdater =
160     AtomicReferenceFieldUpdater.<Semaphore, Node>newUpdater
161     (Semaphore.class, Node.class, "head");
162     private static final
163     AtomicIntegerFieldUpdater<Node> statusUpdater =
164     AtomicIntegerFieldUpdater.<Node>newUpdater
165     (Node.class, "status");
166 dl 1.2
167 tim 1.1
168 dl 1.16 /**
169     * Insert node into queue, initializing head and tail if necessary.
170     * @param node the node to insert
171 dl 1.4 */
172 dl 1.16 private void enq(Node node) {
173     Node t = tail;
174     if (t == null) { // Must initialize first
175     Node h = new Node(null);
176     while ((t = tail) == null) {
177     if (headUpdater.compareAndSet(this, null, h))
178     tail = h;
179     }
180     }
181    
182     for (;;) {
183     node.prev = t; // Prev field must be valid before/upon CAS
184     if (tailUpdater.compareAndSet(this, t, node)) {
185     t.next = node; // Next field assignment lags CAS
186     return;
187     }
188     t = tail;
189     }
190     }
191    
192     /**
193     * Unblock the successor of node
194     * @param node the node
195     */
196     private void unparkSuccessor(Node node) {
197     statusUpdater.compareAndSet(node, SIGNAL, 0);
198     Node s = node.next;
199     if (s == null || s.status == CANCELLED) {
200     s = tail;
201     if (s != null && s != node) {
202     Node p = s.prev;
203     while (p != null && p != node) {
204     if (p.status != CANCELLED)
205     s = p;
206     p = p.prev;
207     }
208     }
209     }
210 dl 1.17 if (s != null && s != node)
211 dl 1.16 LockSupport.unpark(s.thread);
212     }
213    
214    
215     /**
216     * Internal version of tryAcquire returning number of remaining
217     * permits, which is nonnegative only if the acquire succeeded.
218     * @param permits requested number of permits
219     * @return remaining number of permits
220     */
221     private int doTryAcquire(int permits) {
222 dl 1.20 final AtomicInteger perms = this.perms;
223 dl 1.16 for (;;) {
224     int available = perms.get();
225     int remaining = available - permits;
226     if (remaining < 0 ||
227     perms.compareAndSet(available, remaining))
228     return remaining;
229     }
230     }
231    
232     /**
233     * Main code for untimed acquires.
234     * @param permits number of permits requested
235     * @param interrupts interrupt control: -1 for abort on interrupt,
236     * 0 for continue on interrupt
237     * @return true if lock acquired (can be false only if interruptible)
238     */
239     private boolean doAcquire(int permits, int interrupts) {
240     // Fast path bypasses queue
241     if ((!fair || head == tail) && doTryAcquire(permits) >= 0)
242     return true;
243     Thread current = Thread.currentThread();
244     Node node = new Node(current);
245     // Retry fast path before enqueuing
246     if (!fair && doTryAcquire(permits) >= 0)
247     return true;
248     enq(node);
249    
250     for (;;) {
251     Node p = node.prev;
252     if (p == head) {
253     int remaining = doTryAcquire(permits);
254     if (remaining >= 0) {
255     p.next = null;
256     node.thread = null;
257     node.prev = null;
258     head = node;
259     // if still some permits left, wake up successor
260     if (remaining > 0 && node.status < 0)
261     unparkSuccessor(node);
262     if (interrupts > 0) // Re-interrupt on normal exit
263     current.interrupt();
264     return true;
265     }
266     }
267     int status = p.status;
268     if (status == 0)
269     statusUpdater.compareAndSet(p, 0, SIGNAL);
270     else if (status == CANCELLED)
271     node.prev = p.prev;
272     else {
273     assert (status == SIGNAL);
274     LockSupport.park();
275     if (Thread.interrupted()) {
276     if (interrupts < 0) {
277     node.thread = null;
278     node.status = CANCELLED;
279     unparkSuccessor(node);
280     return false;
281     }
282     interrupts = 1; // set to re-interrupt on exit
283     }
284     }
285     }
286     }
287    
288     /**
289     * Main code for timed acquires. Same as doAcquire but with
290     * interspersed time checks.
291     * @param permits number of permits requested
292     * @param nanos timeout in nanosecs
293     * @return true if lock acquired
294     */
295     private boolean doTimedAcquire(int permits, long nanos) throws InterruptedException {
296     if ((!fair || head == tail) && doTryAcquire(permits) >= 0)
297     return true;
298     Thread current = Thread.currentThread();
299     long lastTime = System.nanoTime();
300     Node node = new Node(current);
301     // Retry fast path before enqueuing
302     if (!fair && doTryAcquire(permits) >= 0)
303     return true;
304     enq(node);
305    
306     for (;;) {
307     Node p = node.prev;
308     if (p == head) {
309     int remaining = doTryAcquire(permits);
310     if (remaining >= 0) {
311     p.next = null;
312     node.thread = null;
313     node.prev = null;
314     head = node;
315     if (remaining > 0 && node.status < 0)
316     unparkSuccessor(node);
317     return true;
318     }
319     }
320     if (nanos <= 0L) {
321     node.thread = null;
322     node.status = CANCELLED;
323     unparkSuccessor(node);
324     return false;
325     }
326    
327     int status = p.status;
328     if (status == 0)
329     statusUpdater.compareAndSet(p, 0, SIGNAL);
330     else if (status == CANCELLED)
331     node.prev = p.prev;
332     else {
333     LockSupport.parkNanos(nanos);
334     if (Thread.interrupted()) {
335     node.thread = null;
336     node.status = CANCELLED;
337     unparkSuccessor(node);
338     throw new InterruptedException();
339     }
340     long now = System.nanoTime();
341     nanos -= now - lastTime;
342     lastTime = now;
343     }
344     }
345     }
346    
347     /**
348     * Internal version of release
349     */
350     private void doRelease(int permits) {
351 dl 1.20 final AtomicInteger perms = this.perms;
352 dl 1.16 for (;;) {
353     int p = perms.get();
354     if (perms.compareAndSet(p, p + permits)) {
355     Node h = head;
356     if (h != null && h.status < 0)
357     unparkSuccessor(h);
358     return;
359     }
360     }
361 dl 1.2 }
362 tim 1.1
363     /**
364     * Construct a <tt>Semaphore</tt> with the given number of
365 dl 1.19 * permits and the given fairness setting.
366 dl 1.16 * @param permits the initial number of permits available. This
367     * value may be negative, in which case releases must
368     * occur before any acquires will be granted.
369     * @param fair true if this semaphore will guarantee first-in
370     * first-out granting of permits under contention, else false.
371 tim 1.1 */
372 dl 1.16 public Semaphore(int permits, boolean fair) {
373     this.fair = fair;
374     perms = new AtomicInteger(permits);
375 tim 1.1 }
376    
377     /**
378     * Acquires a permit from this semaphore, blocking until one is
379     * available, or the thread is {@link Thread#interrupt interrupted}.
380     *
381     * <p>Acquires a permit, if one is available and returns immediately,
382     * reducing the number of available permits by one.
383     * <p>If no permit is available then the current thread becomes
384     * disabled for thread scheduling purposes and lies dormant until
385     * one of two things happens:
386     * <ul>
387     * <li>Some other thread invokes the {@link #release} method for this
388 dl 1.16 * semaphore and the current thread is next to be assigned a permit; or
389 tim 1.1 * <li>Some other thread {@link Thread#interrupt interrupts} the current
390     * thread.
391     * </ul>
392     *
393     * <p>If the current thread:
394     * <ul>
395     * <li>has its interrupted status set on entry to this method; or
396     * <li>is {@link Thread#interrupt interrupted} while waiting
397     * for a permit,
398     * </ul>
399     * then {@link InterruptedException} is thrown and the current thread's
400     * interrupted status is cleared.
401     *
402     * @throws InterruptedException if the current thread is interrupted
403     *
404     * @see Thread#interrupt
405     */
406 dl 1.2 public void acquire() throws InterruptedException {
407 dl 1.16 if (Thread.interrupted() || !doAcquire(1, -1))
408     throw new InterruptedException();
409 dl 1.2 }
410 tim 1.1
411     /**
412     * Acquires a permit from this semaphore, blocking until one is
413     * available.
414     *
415     * <p>Acquires a permit, if one is available and returns immediately,
416     * reducing the number of available permits by one.
417     * <p>If no permit is available then the current thread becomes
418     * disabled for thread scheduling purposes and lies dormant until
419     * some other thread invokes the {@link #release} method for this
420 dl 1.16 * semaphore and the current thread is next to be assigned a permit.
421 tim 1.1 *
422     * <p>If the current thread
423     * is {@link Thread#interrupt interrupted} while waiting
424     * for a permit then it will continue to wait, but the time at which
425     * the thread is assigned a permit may change compared to the time it
426     * would have received the permit had no interruption occurred. When the
427     * thread does return from this method its interrupt status will be set.
428     *
429     */
430 dl 1.2 public void acquireUninterruptibly() {
431 dl 1.16 doAcquire(1, 0);
432 dl 1.2 }
433 tim 1.1
434     /**
435     * Acquires a permit from this semaphore, only if one is available at the
436     * time of invocation.
437     * <p>Acquires a permit, if one is available and returns immediately,
438     * with the value <tt>true</tt>,
439     * reducing the number of available permits by one.
440     *
441     * <p>If no permit is available then this method will return
442     * immediately with the value <tt>false</tt>.
443     *
444     * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
445     * otherwise.
446     */
447     public boolean tryAcquire() {
448 dl 1.16 return doTryAcquire(1) >= 0;
449 tim 1.1 }
450    
451     /**
452     * Acquires a permit from this semaphore, if one becomes available
453     * within the given waiting time and the
454     * current thread has not been {@link Thread#interrupt interrupted}.
455     * <p>Acquires a permit, if one is available and returns immediately,
456     * with the value <tt>true</tt>,
457     * reducing the number of available permits by one.
458     * <p>If no permit is available then
459     * the current thread becomes disabled for thread scheduling
460     * purposes and lies dormant until one of three things happens:
461     * <ul>
462     * <li>Some other thread invokes the {@link #release} method for this
463 dl 1.16 * semaphore and the current thread is next to be assigned a permit; or
464 tim 1.1 * <li>Some other thread {@link Thread#interrupt interrupts} the current
465     * thread; or
466     * <li>The specified waiting time elapses.
467     * </ul>
468     * <p>If a permit is acquired then the value <tt>true</tt> is returned.
469     * <p>If the current thread:
470     * <ul>
471     * <li>has its interrupted status set on entry to this method; or
472     * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
473     * a permit,
474     * </ul>
475     * then {@link InterruptedException} is thrown and the current thread's
476     * interrupted status is cleared.
477     * <p>If the specified waiting time elapses then the value <tt>false</tt>
478     * is returned.
479 dl 1.16 * If the time is less than or equal to zero, the method will not wait
480     * at all.
481 tim 1.1 *
482     * @param timeout the maximum time to wait for a permit
483 dl 1.13 * @param unit the time unit of the <tt>timeout</tt> argument.
484 tim 1.1 * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
485     * if the waiting time elapsed before a permit was acquired.
486     *
487     * @throws InterruptedException if the current thread is interrupted
488     *
489     * @see Thread#interrupt
490     *
491     */
492 dl 1.16 public boolean tryAcquire(long timeout, TimeUnit unit)
493 tim 1.1 throws InterruptedException {
494 dl 1.16 if (unit == null)
495     throw new NullPointerException();
496     if (Thread.interrupted())
497     throw new InterruptedException();
498     return doTimedAcquire(1, unit.toNanos(timeout));
499 tim 1.1 }
500    
501     /**
502     * Releases a permit, returning it to the semaphore.
503     * <p>Releases a permit, increasing the number of available permits
504     * by one.
505     * If any threads are blocking trying to acquire a permit, then one
506     * is selected and given the permit that was just released.
507     * That thread is re-enabled for thread scheduling purposes.
508     * <p>There is no requirement that a thread that releases a permit must
509     * have acquired that permit by calling {@link #acquire}.
510     * Correct usage of a semaphore is established by programming convention
511     * in the application.
512     */
513 dl 1.2 public void release() {
514 dl 1.16 doRelease(1);
515     }
516    
517     /**
518     * Acquires the given number of permits from this semaphore,
519     * blocking until all are available,
520     * or the thread is {@link Thread#interrupt interrupted}.
521     *
522     * <p>Acquires the given number of permits, if they are available,
523     * and returns immediately,
524     * reducing the number of available permits by the given amount.
525     *
526     * <p>If insufficient permits are available then the current thread becomes
527     * disabled for thread scheduling purposes and lies dormant until
528     * one of two things happens:
529     * <ul>
530     * <li>Some other thread invokes one of the {@link #release() release}
531     * methods for this semaphore, the current thread is next to be assigned
532     * permits and the number of available permits satisfies this request; or
533     * <li>Some other thread {@link Thread#interrupt interrupts} the current
534     * thread.
535     * </ul>
536     *
537     * <p>If the current thread:
538     * <ul>
539     * <li>has its interrupted status set on entry to this method; or
540     * <li>is {@link Thread#interrupt interrupted} while waiting
541     * for a permit,
542     * </ul>
543     * then {@link InterruptedException} is thrown and the current thread's
544     * interrupted status is cleared.
545 dl 1.19 * Any permits that were to be assigned to this thread are instead
546 dl 1.16 * assigned to the next waiting thread(s), as if
547     * they had been made available by a call to {@link #release()}.
548     *
549     * @param permits the number of permits to acquire
550     *
551     * @throws InterruptedException if the current thread is interrupted
552     * @throws IllegalArgumentException if permits less than zero.
553     *
554     * @see Thread#interrupt
555     */
556     public void acquire(int permits) throws InterruptedException {
557     if (permits < 0) throw new IllegalArgumentException();
558     if (Thread.interrupted() || !doAcquire(permits, -1))
559     throw new InterruptedException();
560     }
561    
562     /**
563     * Acquires the given number of permits from this semaphore,
564     * blocking until all are available.
565     *
566     * <p>Acquires the given number of permits, if they are available,
567     * and returns immediately,
568     * reducing the number of available permits by the given amount.
569     *
570     * <p>If insufficient permits are available then the current thread becomes
571     * disabled for thread scheduling purposes and lies dormant until
572     * some other thread invokes one of the {@link #release() release}
573     * methods for this semaphore, the current thread is next to be assigned
574     * permits and the number of available permits satisfies this request.
575     *
576     * <p>If the current thread
577     * is {@link Thread#interrupt interrupted} while waiting
578     * for permits then it will continue to wait and its position in the
579     * queue is not affected. When the
580     * thread does return from this method its interrupt status will be set.
581     *
582     * @param permits the number of permits to acquire
583     * @throws IllegalArgumentException if permits less than zero.
584     *
585     */
586     public void acquireUninterruptibly(int permits) {
587     if (permits < 0) throw new IllegalArgumentException();
588     doAcquire(permits, 0);
589     }
590    
591     /**
592     * Acquires the given number of permits from this semaphore, only if
593     * all are available at the time of invocation.
594     * <p>Acquires the given number of permits, if they are available, and
595     * returns immediately, with the value <tt>true</tt>,
596     * reducing the number of available permits by the given amount.
597     *
598     * <p>If insufficient permits are available then this method will return
599     * immediately with the value <tt>false</tt> and the number of available
600     * permits is unchanged.
601     *
602     * @param permits the number of permits to acquire
603     *
604     * @return <tt>true</tt> if the permits were acquired and <tt>false</tt>
605     * otherwise.
606     * @throws IllegalArgumentException if permits less than zero.
607     */
608     public boolean tryAcquire(int permits) {
609     if (permits < 0) throw new IllegalArgumentException();
610     return doTryAcquire(permits) >= 0;
611     }
612    
613     /**
614     * Acquires the given number of permits from this semaphore, if all
615     * become available within the given waiting time and the
616     * current thread has not been {@link Thread#interrupt interrupted}.
617     * <p>Acquires the given number of permits, if they are available and
618     * returns immediately, with the value <tt>true</tt>,
619     * reducing the number of available permits by the given amount.
620     * <p>If insufficient permits are available then
621     * the current thread becomes disabled for thread scheduling
622     * purposes and lies dormant until one of three things happens:
623     * <ul>
624     * <li>Some other thread invokes one of the {@link #release() release}
625     * methods for this semaphore, the current thread is next to be assigned
626     * permits and the number of available permits satisfies this request; or
627     * <li>Some other thread {@link Thread#interrupt interrupts} the current
628     * thread; or
629     * <li>The specified waiting time elapses.
630     * </ul>
631     * <p>If the permits are acquired then the value <tt>true</tt> is returned.
632     * <p>If the current thread:
633     * <ul>
634     * <li>has its interrupted status set on entry to this method; or
635     * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
636     * the permits,
637     * </ul>
638     * then {@link InterruptedException} is thrown and the current thread's
639     * interrupted status is cleared.
640     * Any permits that were to be assigned to this thread, are instead
641     * assigned to the next waiting thread(s), as if
642     * they had been made available by a call to {@link #release()}.
643     *
644     * <p>If the specified waiting time elapses then the value <tt>false</tt>
645     * is returned.
646     * If the time is
647     * less than or equal to zero, the method will not wait at all.
648     * Any permits that were to be assigned to this thread, are instead
649     * assigned to the next waiting thread(s), as if
650     * they had been made available by a call to {@link #release()}.
651     *
652     * @param permits the number of permits to acquire
653     * @param timeout the maximum time to wait for the permits
654     * @param unit the time unit of the <tt>timeout</tt> argument.
655     * @return <tt>true</tt> if all permits were acquired and <tt>false</tt>
656     * if the waiting time elapsed before all permits were acquired.
657     *
658     * @throws InterruptedException if the current thread is interrupted
659     * @throws IllegalArgumentException if permits less than zero.
660     *
661     * @see Thread#interrupt
662     *
663     */
664     public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
665     throws InterruptedException {
666     if (permits < 0) throw new IllegalArgumentException();
667     if (unit == null)
668     throw new NullPointerException();
669     if (Thread.interrupted())
670     throw new InterruptedException();
671     return doTimedAcquire(permits, unit.toNanos(timeout));
672     }
673    
674    
675     /**
676     * Releases the given number of permits, returning them to the semaphore.
677     * <p>Releases the given number of permits, increasing the number of
678     * available permits by that amount.
679     * If any threads are blocking trying to acquire permits, then the
680 dl 1.19 * one that has been waiting the longest
681 dl 1.16 * is selected and given the permits that were just released.
682     * If the number of available permits satisfies that thread's request
683     * then that thread is re-enabled for thread scheduling purposes; otherwise
684     * the thread continues to wait. If there are still permits available
685     * after the first thread's request has been satisfied, then those permits
686     * are assigned to the next waiting thread. If it is satisfied then it is
687     * re-enabled for thread scheduling purposes. This continues until there
688     * are insufficient permits to satisfy the next waiting thread, or there
689     * are no more waiting threads.
690     *
691     * <p>There is no requirement that a thread that releases a permit must
692     * have acquired that permit by calling {@link Semaphore#acquire acquire}.
693     * Correct usage of a semaphore is established by programming convention
694     * in the application.
695     *
696     * @param permits the number of permits to release
697     * @throws IllegalArgumentException if permits less than zero.
698     */
699     public void release(int permits) {
700     if (permits < 0) throw new IllegalArgumentException();
701     doRelease(permits);
702 dl 1.2 }
703 tim 1.1
704     /**
705     * Return the current number of permits available in this semaphore.
706     * <p>This method is typically used for debugging and testing purposes.
707     * @return the number of permits available in this semaphore.
708     */
709 dl 1.16 public int availablePermits() {
710     return perms.get();
711 tim 1.1 }
712 dl 1.15
713     /**
714     * Shrink the number of available permits by the indicated
715     * reduction. This method can be useful in subclasses that
716     * use semaphores to track available resources that become
717     * unavailable. This method differs from <tt>acquire</tt>
718     * in that it does not block waiting for permits to become
719     * available.
720     * @param reduction the number of permits to remove
721     * @throws IllegalArgumentException if reduction is negative
722     */
723 dl 1.16 protected void reducePermits(int reduction) {
724 dl 1.15 if (reduction < 0) throw new IllegalArgumentException();
725 dl 1.16 perms.getAndAdd(-reduction);
726     }
727    
728     /**
729     * Return true if this semaphore has fairness set true.
730     * @return true if this semaphore has fairness set true.
731     */
732     public boolean isFair() {
733     return fair;
734 dl 1.15 }
735 dl 1.16
736     /**
737     * Returns an estimate of the number of threads waiting to acquire
738     * a permit. The value is only an estimate because the number of
739     * threads may change dynamically while this method traverses
740     * internal data structures. This method is designed for use in
741     * monitoring of the system state, not for synchronization
742     * control.
743     * @return the estimated number of threads waiting for a permit
744     */
745     public int getQueueLength() {
746     int n = 0;
747     for (Node p = tail; p != null && p != head; p = p.prev)
748     ++n;
749     return n;
750     }
751    
752     /**
753     * Returns a collection containing threads that may be waiting to
754     * acquire a permit. Because the actual set of threads may
755     * change dynamically while constructing this result, the returned
756     * collection is only a best-effort estimate. The elements of the
757     * returned collection are in no particular order. This method is
758     * designed to facilitate construction of subclasses that provide
759     * more extensive monitoring facilities.
760     * @return the collection of threads
761     */
762     protected Collection<Thread> getQueuedThreads() {
763     ArrayList<Thread> list = new ArrayList<Thread>();
764     for (Node p = tail; p != null; p = p.prev) {
765     Thread t = p.thread;
766     if (t != null)
767     list.add(t);
768     }
769     return list;
770     }
771    
772 tim 1.1 }