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