ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.39
Committed: Sun Jan 11 16:02:17 2004 UTC (20 years, 4 months ago) by dl
Branch: MAIN
Changes since 1.38: +4 -4 lines
Log Message:
Simplify/shorten AQS method names

File Contents

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