ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.28
Committed: Tue Dec 30 15:47:48 2003 UTC (20 years, 5 months ago) by dl
Branch: MAIN
Changes since 1.27: +9 -26 lines
Log Message:
Avoid cache threashing

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