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
7 /*package java.util.concurrent;
9 import java.util.concurrent.locks.*;
10 import java.util.concurrent.atomic.*;*/
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 {@code Semaphore} just
18 * keeps a count of the number available and acts accordingly.
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:
25 * private static final int MAX_AVAILABLE = 100;
26 * private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
28 * public Object getItem() throws InterruptedException {
29 * available.acquire();
30 * return getNextAvailableItem();
33 * public void putItem(Object x) {
34 * if (markAsUnused(x))
35 * available.release();
38 * // Not a particularly efficient data structure; just for demo
40 * protected Object[] items = ... whatever kinds of items being managed
41 * protected boolean[] used = new boolean[MAX_AVAILABLE];
43 * protected synchronized Object getNextAvailableItem() {
44 * for (int i = 0; i < MAX_AVAILABLE; ++i) {
50 * return null; // not reached
53 * protected synchronized boolean markAsUnused(Object item) {
54 * for (int i = 0; i < MAX_AVAILABLE; ++i) {
55 * if (item == items[i]) {
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
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 "lock" 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.
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 * {@code acquire} 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
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.
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.
121 * <p>Memory consistency effects: Actions in a thread prior to calling
122 * a "release" method such as {@code release()}
123 * <a href="package-summary.html#MemoryVisibility"><i>happen-before</i></a>
124 * actions following a successful "acquire" method such as {@code acquire()}
132 public class Semaphore implements /*java.io.*/Serializable {
133 private static final long serialVersionUID = -3222578661600680210L;
134 private final int count;
135 private final boolean fair;
136 /** All mechanics via AbstractQueuedSynchronizer subclass */
137 //private final Sync sync;
140 * Synchronization implementation for semaphore. Uses AQS state
141 * to represent permits. Subclassed into fair and nonfair
144 /* abstract static class Sync extends AbstractQueuedSynchronizer {
145 private static final long serialVersionUID = 1192457210091910933L;
151 final int getPermits() {
155 final int nonfairTryAcquireShared(int acquires) {
157 int available = getState();
158 int remaining = available - acquires;
160 compareAndSetState(available, remaining))
165 protected final boolean tryReleaseShared(int releases) {
168 if (compareAndSetState(p, p + releases))
173 final void reducePermits(int reductions) {
175 int current = getState();
176 int next = current - reductions;
177 if (compareAndSetState(current, next))
182 final int drainPermits() {
184 int current = getState();
185 if (current == 0 || compareAndSetState(current, 0))
194 /*final static class NonfairSync extends Sync {
195 private static final long serialVersionUID = -2694183684443567898L;
197 NonfairSync(int permits) {
201 protected int tryAcquireShared(int acquires) {
202 return nonfairTryAcquireShared(acquires);
209 /*final static class FairSync extends Sync {
210 private static final long serialVersionUID = 2014338818796000944L;
212 FairSync(int permits) {
216 protected int tryAcquireShared(int acquires) {
217 Thread current = Thread.currentThread();
219 Thread first = getFirstQueuedThread();
220 if (first != null && first != current)
222 int available = getState();
223 int remaining = available - acquires;
225 compareAndSetState(available, remaining))
232 * Creates a {@code Semaphore} with the given number of
233 * permits and nonfair fairness setting.
235 * @param permits the initial number of permits available.
236 * This value may be negative, in which case releases
237 * must occur before any acquires will be granted.
239 public Semaphore(int permits) {
240 //sync = new NonfairSync(permits);
245 * Creates a {@code Semaphore} with the given number of
246 * permits and the given fairness setting.
248 * @param permits the initial number of permits available.
249 * This value may be negative, in which case releases
250 * must occur before any acquires will be granted.
251 * @param fair {@code true} if this semaphore will guarantee
252 * first-in first-out granting of permits under contention,
255 public Semaphore(int permits, boolean fair) {
256 //sync = (fair)? new FairSync(permits) : new NonfairSync(permits);
262 * Acquires a permit from this semaphore, blocking until one is
263 * available, or the thread is {@linkplain Thread#interrupt interrupted}.
265 * <p>Acquires a permit, if one is available and returns immediately,
266 * reducing the number of available permits by one.
268 * <p>If no permit is available then the current thread becomes
269 * disabled for thread scheduling purposes and lies dormant until
270 * one of two things happens:
272 * <li>Some other thread invokes the {@link #release} method for this
273 * semaphore and the current thread is next to be assigned a permit; or
274 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
275 * the current thread.
278 * <p>If the current thread:
280 * <li>has its interrupted status set on entry to this method; or
281 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
284 * then {@link InterruptedException} is thrown and the current thread's
285 * interrupted status is cleared.
287 * @throws InterruptedException if the current thread is interrupted
289 public synchronized void acquire() throws InterruptedException {
290 //sync.acquireSharedInterruptibly(1);
291 //System.out.println("Unimplemented Semaphore.acquire()!");
292 while(this.count == 0) wait();
298 * Acquires a permit from this semaphore, blocking until one is
301 * <p>Acquires a permit, if one is available and returns immediately,
302 * reducing the number of available permits by one.
304 * <p>If no permit is available then the current thread becomes
305 * disabled for thread scheduling purposes and lies dormant until
306 * some other thread invokes the {@link #release} method for this
307 * semaphore and the current thread is next to be assigned a permit.
309 * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
310 * while waiting for a permit then it will continue to wait, but the
311 * time at which the thread is assigned a permit may change compared to
312 * the time it would have received the permit had no interruption
313 * occurred. When the thread does return from this method its interrupt
314 * status will be set.
316 /*public void acquireUninterruptibly() {
317 sync.acquireShared(1);
321 * Acquires a permit from this semaphore, only if one is available at the
322 * time of invocation.
324 * <p>Acquires a permit, if one is available and returns immediately,
325 * with the value {@code true},
326 * reducing the number of available permits by one.
328 * <p>If no permit is available then this method will return
329 * immediately with the value {@code false}.
331 * <p>Even when this semaphore has been set to use a
332 * fair ordering policy, a call to {@code tryAcquire()} <em>will</em>
333 * immediately acquire a permit if one is available, whether or not
334 * other threads are currently waiting.
335 * This "barging" behavior can be useful in certain
336 * circumstances, even though it breaks fairness. If you want to honor
337 * the fairness setting, then use
338 * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) }
339 * which is almost equivalent (it also detects interruption).
341 * @return {@code true} if a permit was acquired and {@code false}
344 /*public boolean tryAcquire() {
345 return sync.nonfairTryAcquireShared(1) >= 0;
349 * Acquires a permit from this semaphore, if one becomes available
350 * within the given waiting time and the current thread has not
351 * been {@linkplain Thread#interrupt interrupted}.
353 * <p>Acquires a permit, if one is available and returns immediately,
354 * with the value {@code true},
355 * reducing the number of available permits by one.
357 * <p>If no permit is available then the current thread becomes
358 * disabled for thread scheduling purposes and lies dormant until
359 * one of three things happens:
361 * <li>Some other thread invokes the {@link #release} method for this
362 * semaphore and the current thread is next to be assigned a permit; or
363 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
364 * the current thread; or
365 * <li>The specified waiting time elapses.
368 * <p>If a permit is acquired then the value {@code true} is returned.
370 * <p>If the current thread:
372 * <li>has its interrupted status set on entry to this method; or
373 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
374 * to acquire a permit,
376 * then {@link InterruptedException} is thrown and the current thread's
377 * interrupted status is cleared.
379 * <p>If the specified waiting time elapses then the value {@code false}
380 * is returned. If the time is less than or equal to zero, the method
381 * will not wait at all.
383 * @param timeout the maximum time to wait for a permit
384 * @param unit the time unit of the {@code timeout} argument
385 * @return {@code true} if a permit was acquired and {@code false}
386 * if the waiting time elapsed before a permit was acquired
387 * @throws InterruptedException if the current thread is interrupted
389 /*public boolean tryAcquire(long timeout, TimeUnit unit)
390 throws InterruptedException {
391 return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
395 * Releases a permit, returning it to the semaphore.
397 * <p>Releases a permit, increasing the number of available permits by
398 * one. If any threads are trying to acquire a permit, then one is
399 * selected and given the permit that was just released. That thread
400 * is (re)enabled for thread scheduling purposes.
402 * <p>There is no requirement that a thread that releases a permit must
403 * have acquired that permit by calling {@link #acquire}.
404 * Correct usage of a semaphore is established by programming convention
405 * in the application.
407 public synchronized void release() {
408 //sync.releaseShared(1);
409 //System.out.println("Unimplemented Semaphore.release()!");
415 * Acquires the given number of permits from this semaphore,
416 * blocking until all are available,
417 * or the thread is {@linkplain Thread#interrupt interrupted}.
419 * <p>Acquires the given number of permits, if they are available,
420 * and returns immediately, reducing the number of available permits
421 * by the given amount.
423 * <p>If insufficient permits are available then the current thread becomes
424 * disabled for thread scheduling purposes and lies dormant until
425 * one of two things happens:
427 * <li>Some other thread invokes one of the {@link #release() release}
428 * methods for this semaphore, the current thread is next to be assigned
429 * permits and the number of available permits satisfies this request; or
430 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
431 * the current thread.
434 * <p>If the current thread:
436 * <li>has its interrupted status set on entry to this method; or
437 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
440 * then {@link InterruptedException} is thrown and the current thread's
441 * interrupted status is cleared.
442 * Any permits that were to be assigned to this thread are instead
443 * assigned to other threads trying to acquire permits, as if
444 * permits had been made available by a call to {@link #release()}.
446 * @param permits the number of permits to acquire
447 * @throws InterruptedException if the current thread is interrupted
448 * @throws IllegalArgumentException if {@code permits} is negative
450 public void acquire(int permits) throws InterruptedException {
451 /*if (permits < 0) throw new IllegalArgumentException();
452 sync.acquireSharedInterruptibly(permits);*/
453 //System.out.println("Unimplemented Semaphore.acquire(int)!");
454 while(this.count < permits) wait();
460 * Acquires the given number of permits from this semaphore,
461 * blocking until all are available.
463 * <p>Acquires the given number of permits, if they are available,
464 * and returns immediately, reducing the number of available permits
465 * by the given amount.
467 * <p>If insufficient permits are available then the current thread becomes
468 * disabled for thread scheduling purposes and lies dormant until
469 * some other thread invokes one of the {@link #release() release}
470 * methods for this semaphore, the current thread is next to be assigned
471 * permits and the number of available permits satisfies this request.
473 * <p>If the current thread is {@linkplain Thread#interrupt interrupted}
474 * while waiting for permits then it will continue to wait and its
475 * position in the queue is not affected. When the thread does return
476 * from this method its interrupt status will be set.
478 * @param permits the number of permits to acquire
479 * @throws IllegalArgumentException if {@code permits} is negative
482 /*public void acquireUninterruptibly(int permits) {
483 if (permits < 0) throw new IllegalArgumentException();
484 sync.acquireShared(permits);
488 * Acquires the given number of permits from this semaphore, only
489 * if all are available at the time of invocation.
491 * <p>Acquires the given number of permits, if they are available, and
492 * returns immediately, with the value {@code true},
493 * reducing the number of available permits by the given amount.
495 * <p>If insufficient permits are available then this method will return
496 * immediately with the value {@code false} and the number of available
497 * permits is unchanged.
499 * <p>Even when this semaphore has been set to use a fair ordering
500 * policy, a call to {@code tryAcquire} <em>will</em>
501 * immediately acquire a permit if one is available, whether or
502 * not other threads are currently waiting. This
503 * "barging" behavior can be useful in certain
504 * circumstances, even though it breaks fairness. If you want to
505 * honor the fairness setting, then use {@link #tryAcquire(int,
506 * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) }
507 * which is almost equivalent (it also detects interruption).
509 * @param permits the number of permits to acquire
510 * @return {@code true} if the permits were acquired and
511 * {@code false} otherwise
512 * @throws IllegalArgumentException if {@code permits} is negative
514 /*public boolean tryAcquire(int permits) {
515 if (permits < 0) throw new IllegalArgumentException();
516 return sync.nonfairTryAcquireShared(permits) >= 0;
520 * Acquires the given number of permits from this semaphore, if all
521 * become available within the given waiting time and the current
522 * thread has not been {@linkplain Thread#interrupt interrupted}.
524 * <p>Acquires the given number of permits, if they are available and
525 * returns immediately, with the value {@code true},
526 * reducing the number of available permits by the given amount.
528 * <p>If insufficient permits are available then
529 * the current thread becomes disabled for thread scheduling
530 * purposes and lies dormant until one of three things happens:
532 * <li>Some other thread invokes one of the {@link #release() release}
533 * methods for this semaphore, the current thread is next to be assigned
534 * permits and the number of available permits satisfies this request; or
535 * <li>Some other thread {@linkplain Thread#interrupt interrupts}
536 * the current thread; or
537 * <li>The specified waiting time elapses.
540 * <p>If the permits are acquired then the value {@code true} is returned.
542 * <p>If the current thread:
544 * <li>has its interrupted status set on entry to this method; or
545 * <li>is {@linkplain Thread#interrupt interrupted} while waiting
546 * to acquire the permits,
548 * then {@link InterruptedException} is thrown and the current thread's
549 * interrupted status is cleared.
550 * Any permits that were to be assigned to this thread, are instead
551 * assigned to other threads trying to acquire permits, as if
552 * the permits had been made available by a call to {@link #release()}.
554 * <p>If the specified waiting time elapses then the value {@code false}
555 * is returned. If the time is less than or equal to zero, the method
556 * will not wait at all. Any permits that were to be assigned to this
557 * thread, are instead assigned to other threads trying to acquire
558 * permits, as if the permits had been made available by a call to
559 * {@link #release()}.
561 * @param permits the number of permits to acquire
562 * @param timeout the maximum time to wait for the permits
563 * @param unit the time unit of the {@code timeout} argument
564 * @return {@code true} if all permits were acquired and {@code false}
565 * if the waiting time elapsed before all permits were acquired
566 * @throws InterruptedException if the current thread is interrupted
567 * @throws IllegalArgumentException if {@code permits} is negative
569 /*public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
570 throws InterruptedException {
571 if (permits < 0) throw new IllegalArgumentException();
572 return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
576 * Releases the given number of permits, returning them to the semaphore.
578 * <p>Releases the given number of permits, increasing the number of
579 * available permits by that amount.
580 * If any threads are trying to acquire permits, then one
581 * is selected and given the permits that were just released.
582 * If the number of available permits satisfies that thread's request
583 * then that thread is (re)enabled for thread scheduling purposes;
584 * otherwise the thread will wait until sufficient permits are available.
585 * If there are still permits available
586 * after this thread's request has been satisfied, then those permits
587 * are assigned in turn to other threads trying to acquire permits.
589 * <p>There is no requirement that a thread that releases a permit must
590 * have acquired that permit by calling {@link Semaphore#acquire acquire}.
591 * Correct usage of a semaphore is established by programming convention
592 * in the application.
594 * @param permits the number of permits to release
595 * @throws IllegalArgumentException if {@code permits} is negative
597 public void release(int permits) {
598 /*if (permits < 0) throw new IllegalArgumentException();
599 sync.releaseShared(permits);*/
600 //System.out.println("Unimplemented Semaphore.release()!");
606 * Returns the current number of permits available in this semaphore.
608 * <p>This method is typically used for debugging and testing purposes.
610 * @return the number of permits available in this semaphore
612 /*public int availablePermits() {
613 return sync.getPermits();
617 * Acquires and returns all permits that are immediately available.
619 * @return the number of permits acquired
621 /*public int drainPermits() {
622 return sync.drainPermits();
626 * Shrinks the number of available permits by the indicated
627 * reduction. This method can be useful in subclasses that use
628 * semaphores to track resources that become unavailable. This
629 * method differs from {@code acquire} in that it does not block
630 * waiting for permits to become available.
632 * @param reduction the number of permits to remove
633 * @throws IllegalArgumentException if {@code reduction} is negative
635 /*protected void reducePermits(int reduction) {
636 if (reduction < 0) throw new IllegalArgumentException();
637 sync.reducePermits(reduction);
641 * Returns {@code true} if this semaphore has fairness set true.
643 * @return {@code true} if this semaphore has fairness set true
645 /*public boolean isFair() {
646 return sync instanceof FairSync;
650 * Queries whether any threads are waiting to acquire. Note that
651 * because cancellations may occur at any time, a {@code true}
652 * return does not guarantee that any other thread will ever
653 * acquire. This method is designed primarily for use in
654 * monitoring of the system state.
656 * @return {@code true} if there may be other threads waiting to
659 /*public final boolean hasQueuedThreads() {
660 return sync.hasQueuedThreads();
664 * Returns an estimate of the number of threads waiting to acquire.
665 * The value is only an estimate because the number of threads may
666 * change dynamically while this method traverses internal data
667 * structures. This method is designed for use in monitoring of the
668 * system state, not for synchronization control.
670 * @return the estimated number of threads waiting for this lock
672 /*public final int getQueueLength() {
673 return sync.getQueueLength();
677 * Returns a collection containing threads that may be waiting to acquire.
678 * Because the actual set of threads may change dynamically while
679 * constructing this result, the returned collection is only a best-effort
680 * estimate. The elements of the returned collection are in no particular
681 * order. This method is designed to facilitate construction of
682 * subclasses that provide more extensive monitoring facilities.
684 * @return the collection of threads
686 /*protected Collection<Thread> getQueuedThreads() {
687 return sync.getQueuedThreads();
691 * Returns a string identifying this semaphore, as well as its state.
692 * The state, in brackets, includes the String {@code "Permits ="}
693 * followed by the number of permits.
695 * @return a string identifying this semaphore, as well as its state
697 /*public String toString() {
698 return super.toString() + "[Permits = " + sync.getPermits() + "]";