ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.24
Committed: Sat Dec 27 19:26:26 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.23: +2 -2 lines
Log Message:
Headers reference Creative Commons

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