ViewVC Help
View File | Revision Log | Show Annotations | Download File | Root Listing
root/jsr166/jsr166/src/main/java/util/concurrent/Semaphore.java
Revision: 1.46
Committed: Mon Jun 13 18:41:16 2005 UTC (19 years ago) by dl
Branch: MAIN
Changes since 1.45: +6 -0 lines
Log Message:
Add serial ids

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