ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.25
Committed: Sun Dec 28 15:53:16 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.24: +12 -11 lines
Log Message:
Adjust to AQS changes

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     * http://creativecommons.org/licenses/publicdomain
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 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.23 public class Semaphore implements java.io.Serializable {
122 dl 1.16 private static final long serialVersionUID = -3222578661600680210L;
123 dl 1.25 /** All mechanics via AbstractQueuedSynchronizer subclass */
124 dl 1.23 private final Sync sync;
125    
126 dl 1.25 /**
127     * Synchronization implementation for semaphore
128     */
129 dl 1.23 private final static class Sync extends AbstractQueuedSynchronizer {
130     final boolean fair;
131     Sync(int permits, boolean fair) {
132     this.fair = fair;
133 dl 1.25 state().set(permits);
134 dl 1.23 }
135    
136     public final int acquireSharedState(boolean isQueued, int acquires,
137     Thread current) {
138 dl 1.25 final AtomicInteger perms = state();
139     if (!isQueued && fair && hasQueuedThreads())
140 dl 1.23 return -1;
141     for (;;) {
142     int available = perms.get();
143     int remaining = available - acquires;
144     if (remaining < 0 ||
145     perms.compareAndSet(available, remaining))
146     return remaining;
147     }
148     }
149    
150     public final boolean releaseSharedState(int releases) {
151 dl 1.25 final AtomicInteger perms = state();
152 dl 1.23 for (;;) {
153     int p = perms.get();
154     if (perms.compareAndSet(p, p + releases))
155     return true;
156     }
157     }
158    
159     public final int acquireExclusiveState(boolean isQueued,
160     int acquires,
161     Thread current) {
162     throw new UnsupportedOperationException();
163     }
164    
165     public final boolean releaseExclusiveState(int releases) {
166     throw new UnsupportedOperationException();
167     }
168    
169     public final void checkConditionAccess(Thread thread, boolean waiting) {
170     throw new UnsupportedOperationException();
171     }
172     }
173 dl 1.16
174 tim 1.1 /**
175     * Construct a <tt>Semaphore</tt> with the given number of
176 dl 1.19 * permits and the given fairness setting.
177 dl 1.16 * @param permits the initial number of permits available. This
178     * value may be negative, in which case releases must
179     * occur before any acquires will be granted.
180     * @param fair true if this semaphore will guarantee first-in
181     * first-out granting of permits under contention, else false.
182 tim 1.1 */
183 dl 1.16 public Semaphore(int permits, boolean fair) {
184 dl 1.23 sync = new Sync(permits, fair);
185 tim 1.1 }
186    
187     /**
188     * Acquires a permit from this semaphore, blocking until one is
189     * available, or the thread is {@link Thread#interrupt interrupted}.
190     *
191     * <p>Acquires a permit, if one is available and returns immediately,
192     * reducing the number of available permits by one.
193     * <p>If no permit is available then the current thread becomes
194     * disabled for thread scheduling purposes and lies dormant until
195     * one of two things happens:
196     * <ul>
197     * <li>Some other thread invokes the {@link #release} method for this
198 dl 1.16 * semaphore and the current thread is next to be assigned a permit; or
199 tim 1.1 * <li>Some other thread {@link Thread#interrupt interrupts} the current
200     * thread.
201     * </ul>
202     *
203     * <p>If the current thread:
204     * <ul>
205     * <li>has its interrupted status set on entry to this method; or
206     * <li>is {@link Thread#interrupt interrupted} while waiting
207     * for a permit,
208     * </ul>
209     * then {@link InterruptedException} is thrown and the current thread's
210     * interrupted status is cleared.
211     *
212     * @throws InterruptedException if the current thread is interrupted
213     *
214     * @see Thread#interrupt
215     */
216 dl 1.2 public void acquire() throws InterruptedException {
217 dl 1.23 sync.acquireSharedInterruptibly(1);
218 dl 1.2 }
219 tim 1.1
220     /**
221     * Acquires a permit from this semaphore, blocking until one is
222     * available.
223     *
224     * <p>Acquires a permit, if one is available and returns immediately,
225     * reducing the number of available permits by one.
226     * <p>If no permit is available then the current thread becomes
227     * disabled for thread scheduling purposes and lies dormant until
228     * some other thread invokes the {@link #release} method for this
229 dl 1.16 * semaphore and the current thread is next to be assigned a permit.
230 tim 1.1 *
231     * <p>If the current thread
232     * is {@link Thread#interrupt interrupted} while waiting
233     * for a permit then it will continue to wait, but the time at which
234     * the thread is assigned a permit may change compared to the time it
235     * would have received the permit had no interruption occurred. When the
236     * thread does return from this method its interrupt status will be set.
237     *
238     */
239 dl 1.2 public void acquireUninterruptibly() {
240 dl 1.23 sync.acquireSharedUninterruptibly(1);
241 dl 1.2 }
242 tim 1.1
243     /**
244     * Acquires a permit from this semaphore, only if one is available at the
245     * time of invocation.
246     * <p>Acquires a permit, if one is available and returns immediately,
247     * with the value <tt>true</tt>,
248     * reducing the number of available permits by one.
249     *
250     * <p>If no permit is available then this method will return
251     * immediately with the value <tt>false</tt>.
252     *
253     * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
254     * otherwise.
255     */
256     public boolean tryAcquire() {
257 dl 1.23 return sync.acquireSharedState(false, 1, null) >= 0;
258 tim 1.1 }
259    
260     /**
261     * Acquires a permit from this semaphore, if one becomes available
262     * within the given waiting time and the
263     * current thread has not been {@link Thread#interrupt interrupted}.
264     * <p>Acquires a permit, if one is available and returns immediately,
265     * with the value <tt>true</tt>,
266     * reducing the number of available permits by one.
267     * <p>If no permit is available then
268     * the current thread becomes disabled for thread scheduling
269     * purposes and lies dormant until one of three things happens:
270     * <ul>
271     * <li>Some other thread invokes the {@link #release} method for this
272 dl 1.16 * semaphore and the current thread is next to be assigned a permit; or
273 tim 1.1 * <li>Some other thread {@link Thread#interrupt interrupts} the current
274     * thread; or
275     * <li>The specified waiting time elapses.
276     * </ul>
277     * <p>If a permit is acquired then the value <tt>true</tt> is returned.
278     * <p>If the current thread:
279     * <ul>
280     * <li>has its interrupted status set on entry to this method; or
281     * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
282     * a permit,
283     * </ul>
284     * then {@link InterruptedException} is thrown and the current thread's
285     * interrupted status is cleared.
286     * <p>If the specified waiting time elapses then the value <tt>false</tt>
287     * is returned.
288 dl 1.16 * If the time is less than or equal to zero, the method will not wait
289     * at all.
290 tim 1.1 *
291     * @param timeout the maximum time to wait for a permit
292 dl 1.13 * @param unit the time unit of the <tt>timeout</tt> argument.
293 tim 1.1 * @return <tt>true</tt> if a permit was acquired and <tt>false</tt>
294     * if the waiting time elapsed before a permit was acquired.
295     *
296     * @throws InterruptedException if the current thread is interrupted
297     *
298     * @see Thread#interrupt
299     *
300     */
301 dl 1.16 public boolean tryAcquire(long timeout, TimeUnit unit)
302 tim 1.1 throws InterruptedException {
303 dl 1.23 return sync.acquireSharedTimed(1, unit.toNanos(timeout));
304 tim 1.1 }
305    
306     /**
307     * Releases a permit, returning it to the semaphore.
308     * <p>Releases a permit, increasing the number of available permits
309     * by one.
310     * If any threads are blocking trying to acquire a permit, then one
311     * is selected and given the permit that was just released.
312     * That thread is re-enabled for thread scheduling purposes.
313     * <p>There is no requirement that a thread that releases a permit must
314     * have acquired that permit by calling {@link #acquire}.
315     * Correct usage of a semaphore is established by programming convention
316     * in the application.
317     */
318 dl 1.2 public void release() {
319 dl 1.23 sync.releaseShared(1);
320 dl 1.16 }
321    
322     /**
323     * Acquires the given number of permits from this semaphore,
324     * blocking until all are available,
325     * or the thread is {@link Thread#interrupt interrupted}.
326     *
327     * <p>Acquires the given number of permits, if they are available,
328     * and returns immediately,
329     * reducing the number of available permits by the given amount.
330     *
331     * <p>If insufficient permits are available then the current thread becomes
332     * disabled for thread scheduling purposes and lies dormant until
333     * one of two things happens:
334     * <ul>
335     * <li>Some other thread invokes one of the {@link #release() release}
336     * methods for this semaphore, the current thread is next to be assigned
337     * permits and the number of available permits satisfies this request; or
338     * <li>Some other thread {@link Thread#interrupt interrupts} the current
339     * thread.
340     * </ul>
341     *
342     * <p>If the current thread:
343     * <ul>
344     * <li>has its interrupted status set on entry to this method; or
345     * <li>is {@link Thread#interrupt interrupted} while waiting
346     * for a permit,
347     * </ul>
348     * then {@link InterruptedException} is thrown and the current thread's
349     * interrupted status is cleared.
350 dl 1.19 * Any permits that were to be assigned to this thread are instead
351 dl 1.16 * assigned to the next waiting thread(s), as if
352     * they had been made available by a call to {@link #release()}.
353     *
354     * @param permits the number of permits to acquire
355     *
356     * @throws InterruptedException if the current thread is interrupted
357     * @throws IllegalArgumentException if permits less than zero.
358     *
359     * @see Thread#interrupt
360     */
361     public void acquire(int permits) throws InterruptedException {
362     if (permits < 0) throw new IllegalArgumentException();
363 dl 1.23 sync.acquireSharedInterruptibly(permits);
364 dl 1.16 }
365    
366     /**
367     * Acquires the given number of permits from this semaphore,
368     * blocking until all are available.
369     *
370     * <p>Acquires the given number of permits, if they are available,
371     * and returns immediately,
372     * reducing the number of available permits by the given amount.
373     *
374     * <p>If insufficient permits are available then the current thread becomes
375     * disabled for thread scheduling purposes and lies dormant until
376     * some other thread invokes one of the {@link #release() release}
377     * methods for this semaphore, the current thread is next to be assigned
378     * permits and the number of available permits satisfies this request.
379     *
380     * <p>If the current thread
381     * is {@link Thread#interrupt interrupted} while waiting
382     * for permits then it will continue to wait and its position in the
383     * queue is not affected. When the
384     * thread does return from this method its interrupt status will be set.
385     *
386     * @param permits the number of permits to acquire
387     * @throws IllegalArgumentException if permits less than zero.
388     *
389     */
390     public void acquireUninterruptibly(int permits) {
391     if (permits < 0) throw new IllegalArgumentException();
392 dl 1.23 sync.acquireSharedUninterruptibly(permits);
393 dl 1.16 }
394    
395     /**
396     * Acquires the given number of permits from this semaphore, only if
397     * all are available at the time of invocation.
398     * <p>Acquires the given number of permits, if they are available, and
399     * returns immediately, with the value <tt>true</tt>,
400     * reducing the number of available permits by the given amount.
401     *
402     * <p>If insufficient permits are available then this method will return
403     * immediately with the value <tt>false</tt> and the number of available
404     * permits is unchanged.
405     *
406     * @param permits the number of permits to acquire
407     *
408     * @return <tt>true</tt> if the permits were acquired and <tt>false</tt>
409     * otherwise.
410     * @throws IllegalArgumentException if permits less than zero.
411     */
412     public boolean tryAcquire(int permits) {
413     if (permits < 0) throw new IllegalArgumentException();
414 dl 1.23 return sync.acquireSharedState(false, permits, null) >= 0;
415 dl 1.16 }
416    
417     /**
418     * Acquires the given number of permits from this semaphore, if all
419     * become available within the given waiting time and the
420     * current thread has not been {@link Thread#interrupt interrupted}.
421     * <p>Acquires the given number of permits, if they are available and
422     * returns immediately, with the value <tt>true</tt>,
423     * reducing the number of available permits by the given amount.
424     * <p>If insufficient permits are available then
425     * the current thread becomes disabled for thread scheduling
426     * purposes and lies dormant until one of three things happens:
427     * <ul>
428     * <li>Some other thread invokes one of the {@link #release() release}
429     * methods for this semaphore, the current thread is next to be assigned
430     * permits and the number of available permits satisfies this request; or
431     * <li>Some other thread {@link Thread#interrupt interrupts} the current
432     * thread; or
433     * <li>The specified waiting time elapses.
434     * </ul>
435     * <p>If the permits are acquired then the value <tt>true</tt> is returned.
436     * <p>If the current thread:
437     * <ul>
438     * <li>has its interrupted status set on entry to this method; or
439     * <li>is {@link Thread#interrupt interrupted} while waiting to acquire
440     * the permits,
441     * </ul>
442     * then {@link InterruptedException} is thrown and the current thread's
443     * interrupted status is cleared.
444     * Any permits that were to be assigned to this thread, are instead
445     * assigned to the next waiting thread(s), as if
446     * they had been made available by a call to {@link #release()}.
447     *
448     * <p>If the specified waiting time elapses then the value <tt>false</tt>
449     * is returned.
450     * If the time is
451     * less than or equal to zero, the method will not wait at all.
452     * Any permits that were to be assigned to this thread, are instead
453     * assigned to the next waiting thread(s), as if
454     * they had been made available by a call to {@link #release()}.
455     *
456     * @param permits the number of permits to acquire
457     * @param timeout the maximum time to wait for the permits
458     * @param unit the time unit of the <tt>timeout</tt> argument.
459     * @return <tt>true</tt> if all permits were acquired and <tt>false</tt>
460     * if the waiting time elapsed before all permits were acquired.
461     *
462     * @throws InterruptedException if the current thread is interrupted
463     * @throws IllegalArgumentException if permits less than zero.
464     *
465     * @see Thread#interrupt
466     *
467     */
468     public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
469     throws InterruptedException {
470     if (permits < 0) throw new IllegalArgumentException();
471 dl 1.23 return sync.acquireSharedTimed(permits, unit.toNanos(timeout));
472 dl 1.16 }
473    
474    
475     /**
476     * Releases the given number of permits, returning them to the semaphore.
477     * <p>Releases the given number of permits, increasing the number of
478     * available permits by that amount.
479     * If any threads are blocking trying to acquire permits, then the
480 dl 1.19 * one that has been waiting the longest
481 dl 1.16 * is selected and given the permits that were just released.
482     * If the number of available permits satisfies that thread's request
483     * then that thread is re-enabled for thread scheduling purposes; otherwise
484     * the thread continues to wait. If there are still permits available
485     * after the first thread's request has been satisfied, then those permits
486     * are assigned to the next waiting thread. If it is satisfied then it is
487     * re-enabled for thread scheduling purposes. This continues until there
488     * are insufficient permits to satisfy the next waiting thread, or there
489     * are no more waiting threads.
490     *
491     * <p>There is no requirement that a thread that releases a permit must
492     * have acquired that permit by calling {@link Semaphore#acquire acquire}.
493     * Correct usage of a semaphore is established by programming convention
494     * in the application.
495     *
496     * @param permits the number of permits to release
497     * @throws IllegalArgumentException if permits less than zero.
498     */
499     public void release(int permits) {
500     if (permits < 0) throw new IllegalArgumentException();
501 dl 1.23 sync.releaseShared(permits);
502 dl 1.2 }
503 tim 1.1
504     /**
505     * Return the current number of permits available in this semaphore.
506     * <p>This method is typically used for debugging and testing purposes.
507     * @return the number of permits available in this semaphore.
508     */
509 dl 1.16 public int availablePermits() {
510 dl 1.25 return sync.state().get();
511 tim 1.1 }
512 dl 1.15
513     /**
514     * Shrink the number of available permits by the indicated
515     * reduction. This method can be useful in subclasses that
516     * use semaphores to track available resources that become
517     * unavailable. This method differs from <tt>acquire</tt>
518     * in that it does not block waiting for permits to become
519     * available.
520     * @param reduction the number of permits to remove
521     * @throws IllegalArgumentException if reduction is negative
522     */
523 dl 1.16 protected void reducePermits(int reduction) {
524 dl 1.15 if (reduction < 0) throw new IllegalArgumentException();
525 dl 1.25 sync.state().getAndAdd(-reduction);
526 dl 1.16 }
527    
528     /**
529     * Return true if this semaphore has fairness set true.
530     * @return true if this semaphore has fairness set true.
531     */
532     public boolean isFair() {
533 dl 1.23 return sync.fair;
534 dl 1.22 }
535    
536    
537     /**
538 dl 1.23 * Queries whether any threads are waiting to acquire. Note that
539     * because cancellations may occur at any time, a <tt>true</tt>
540     * return does not guarantee that any other thread will ever
541     * acquire. This method is designed primarily for use in
542     * monitoring of the system state.
543     *
544     * @return true if there may be other threads waiting to acquire
545     * the lock.
546 dl 1.22 */
547 dl 1.25 public final boolean hasQueuedThreads() {
548     return sync.hasQueuedThreads();
549 dl 1.22 }
550    
551    
552     /**
553 dl 1.23 * Returns an estimate of the number of threads waiting to
554     * acquire. The value is only an estimate because the number of
555     * threads may change dynamically while this method traverses
556     * internal data structures. This method is designed for use in
557     * monitoring of the system state, not for synchronization
558     * control.
559     * @return the estimated number of threads waiting for this lock
560 dl 1.22 */
561 dl 1.23 public final int getQueueLength() {
562     return sync.getQueueLength();
563 dl 1.22 }
564    
565     /**
566 dl 1.23 * Returns a collection containing threads that may be waiting to
567     * acquire. Because the actual set of threads may change
568     * dynamically while constructing this result, the returned
569     * collection is only a best-effort estimate. The elements of the
570     * returned collection are in no particular order. This method is
571     * designed to facilitate construction of subclasses that provide
572     * more extensive monitoring facilities.
573     * @return the collection of threads
574 dl 1.22 */
575 dl 1.23 protected Collection<Thread> getQueuedThreads() {
576     return sync.getQueuedThreads();
577 dl 1.16 }
578 dl 1.23
579 tim 1.1 }