jaroslav@1890: /* jaroslav@1890: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. jaroslav@1890: * jaroslav@1890: * This code is free software; you can redistribute it and/or modify it jaroslav@1890: * under the terms of the GNU General Public License version 2 only, as jaroslav@1890: * published by the Free Software Foundation. Oracle designates this jaroslav@1890: * particular file as subject to the "Classpath" exception as provided jaroslav@1890: * by Oracle in the LICENSE file that accompanied this code. jaroslav@1890: * jaroslav@1890: * This code is distributed in the hope that it will be useful, but WITHOUT jaroslav@1890: * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or jaroslav@1890: * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License jaroslav@1890: * version 2 for more details (a copy is included in the LICENSE file that jaroslav@1890: * accompanied this code). jaroslav@1890: * jaroslav@1890: * You should have received a copy of the GNU General Public License version jaroslav@1890: * 2 along with this work; if not, write to the Free Software Foundation, jaroslav@1890: * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. jaroslav@1890: * jaroslav@1890: * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA jaroslav@1890: * or visit www.oracle.com if you need additional information or have any jaroslav@1890: * questions. jaroslav@1890: */ jaroslav@1890: jaroslav@1890: /* jaroslav@1890: * This file is available under and governed by the GNU General Public jaroslav@1890: * License version 2 only, as published by the Free Software Foundation. jaroslav@1890: * However, the following notice accompanied the original version of this jaroslav@1890: * file: jaroslav@1890: * jaroslav@1890: * Written by Doug Lea with assistance from members of JCP JSR-166 jaroslav@1890: * Expert Group and released to the public domain, as explained at jaroslav@1890: * http://creativecommons.org/publicdomain/zero/1.0/ jaroslav@1890: */ jaroslav@1890: jaroslav@1890: package java.util.concurrent; jaroslav@1890: import java.util.*; jaroslav@1890: import java.util.concurrent.locks.*; jaroslav@1890: import java.util.concurrent.atomic.*; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * A counting semaphore. Conceptually, a semaphore maintains a set of jaroslav@1890: * permits. Each {@link #acquire} blocks if necessary until a permit is jaroslav@1890: * available, and then takes it. Each {@link #release} adds a permit, jaroslav@1890: * potentially releasing a blocking acquirer. jaroslav@1890: * However, no actual permit objects are used; the {@code Semaphore} just jaroslav@1890: * keeps a count of the number available and acts accordingly. jaroslav@1890: * jaroslav@1890: *

Semaphores are often used to restrict the number of threads than can jaroslav@1890: * access some (physical or logical) resource. For example, here is jaroslav@1890: * a class that uses a semaphore to control access to a pool of items: jaroslav@1890: *

jaroslav@1890:  * class Pool {
jaroslav@1890:  *   private static final int MAX_AVAILABLE = 100;
jaroslav@1890:  *   private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
jaroslav@1890:  *
jaroslav@1890:  *   public Object getItem() throws InterruptedException {
jaroslav@1890:  *     available.acquire();
jaroslav@1890:  *     return getNextAvailableItem();
jaroslav@1890:  *   }
jaroslav@1890:  *
jaroslav@1890:  *   public void putItem(Object x) {
jaroslav@1890:  *     if (markAsUnused(x))
jaroslav@1890:  *       available.release();
jaroslav@1890:  *   }
jaroslav@1890:  *
jaroslav@1890:  *   // Not a particularly efficient data structure; just for demo
jaroslav@1890:  *
jaroslav@1890:  *   protected Object[] items = ... whatever kinds of items being managed
jaroslav@1890:  *   protected boolean[] used = new boolean[MAX_AVAILABLE];
jaroslav@1890:  *
jaroslav@1890:  *   protected synchronized Object getNextAvailableItem() {
jaroslav@1890:  *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
jaroslav@1890:  *       if (!used[i]) {
jaroslav@1890:  *          used[i] = true;
jaroslav@1890:  *          return items[i];
jaroslav@1890:  *       }
jaroslav@1890:  *     }
jaroslav@1890:  *     return null; // not reached
jaroslav@1890:  *   }
jaroslav@1890:  *
jaroslav@1890:  *   protected synchronized boolean markAsUnused(Object item) {
jaroslav@1890:  *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
jaroslav@1890:  *       if (item == items[i]) {
jaroslav@1890:  *          if (used[i]) {
jaroslav@1890:  *            used[i] = false;
jaroslav@1890:  *            return true;
jaroslav@1890:  *          } else
jaroslav@1890:  *            return false;
jaroslav@1890:  *       }
jaroslav@1890:  *     }
jaroslav@1890:  *     return false;
jaroslav@1890:  *   }
jaroslav@1890:  *
jaroslav@1890:  * }
jaroslav@1890:  * 
jaroslav@1890: * jaroslav@1890: *

Before obtaining an item each thread must acquire a permit from jaroslav@1890: * the semaphore, guaranteeing that an item is available for use. When jaroslav@1890: * the thread has finished with the item it is returned back to the jaroslav@1890: * pool and a permit is returned to the semaphore, allowing another jaroslav@1890: * thread to acquire that item. Note that no synchronization lock is jaroslav@1890: * held when {@link #acquire} is called as that would prevent an item jaroslav@1890: * from being returned to the pool. The semaphore encapsulates the jaroslav@1890: * synchronization needed to restrict access to the pool, separately jaroslav@1890: * from any synchronization needed to maintain the consistency of the jaroslav@1890: * pool itself. jaroslav@1890: * jaroslav@1890: *

A semaphore initialized to one, and which is used such that it jaroslav@1890: * only has at most one permit available, can serve as a mutual jaroslav@1890: * exclusion lock. This is more commonly known as a binary jaroslav@1890: * semaphore, because it only has two states: one permit jaroslav@1890: * available, or zero permits available. When used in this way, the jaroslav@1890: * binary semaphore has the property (unlike many {@link Lock} jaroslav@1890: * implementations), that the "lock" can be released by a jaroslav@1890: * thread other than the owner (as semaphores have no notion of jaroslav@1890: * ownership). This can be useful in some specialized contexts, such jaroslav@1890: * as deadlock recovery. jaroslav@1890: * jaroslav@1890: *

The constructor for this class optionally accepts a jaroslav@1890: * fairness parameter. When set false, this class makes no jaroslav@1890: * guarantees about the order in which threads acquire permits. In jaroslav@1890: * particular, barging is permitted, that is, a thread jaroslav@1890: * invoking {@link #acquire} can be allocated a permit ahead of a jaroslav@1890: * thread that has been waiting - logically the new thread places itself at jaroslav@1890: * the head of the queue of waiting threads. When fairness is set true, the jaroslav@1890: * semaphore guarantees that threads invoking any of the {@link jaroslav@1890: * #acquire() acquire} methods are selected to obtain permits in the order in jaroslav@1890: * which their invocation of those methods was processed jaroslav@1890: * (first-in-first-out; FIFO). Note that FIFO ordering necessarily jaroslav@1890: * applies to specific internal points of execution within these jaroslav@1890: * methods. So, it is possible for one thread to invoke jaroslav@1890: * {@code acquire} before another, but reach the ordering point after jaroslav@1890: * the other, and similarly upon return from the method. jaroslav@1890: * Also note that the untimed {@link #tryAcquire() tryAcquire} methods do not jaroslav@1890: * honor the fairness setting, but will take any permits that are jaroslav@1890: * available. jaroslav@1890: * jaroslav@1890: *

Generally, semaphores used to control resource access should be jaroslav@1890: * initialized as fair, to ensure that no thread is starved out from jaroslav@1890: * accessing a resource. When using semaphores for other kinds of jaroslav@1890: * synchronization control, the throughput advantages of non-fair jaroslav@1890: * ordering often outweigh fairness considerations. jaroslav@1890: * jaroslav@1890: *

This class also provides convenience methods to {@link jaroslav@1890: * #acquire(int) acquire} and {@link #release(int) release} multiple jaroslav@1890: * permits at a time. Beware of the increased risk of indefinite jaroslav@1890: * postponement when these methods are used without fairness set true. jaroslav@1890: * jaroslav@1890: *

Memory consistency effects: Actions in a thread prior to calling jaroslav@1890: * a "release" method such as {@code release()} jaroslav@1890: * happen-before jaroslav@1890: * actions following a successful "acquire" method such as {@code acquire()} jaroslav@1890: * in another thread. jaroslav@1890: * jaroslav@1890: * @since 1.5 jaroslav@1890: * @author Doug Lea jaroslav@1890: * jaroslav@1890: */ jaroslav@1890: jaroslav@1890: public class Semaphore implements java.io.Serializable { jaroslav@1890: private static final long serialVersionUID = -3222578661600680210L; jaroslav@1890: /** All mechanics via AbstractQueuedSynchronizer subclass */ jaroslav@1890: private final Sync sync; jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Synchronization implementation for semaphore. Uses AQS state jaroslav@1890: * to represent permits. Subclassed into fair and nonfair jaroslav@1890: * versions. jaroslav@1890: */ jaroslav@1890: abstract static class Sync extends AbstractQueuedSynchronizer { jaroslav@1890: private static final long serialVersionUID = 1192457210091910933L; jaroslav@1890: jaroslav@1890: Sync(int permits) { jaroslav@1890: setState(permits); jaroslav@1890: } jaroslav@1890: jaroslav@1890: final int getPermits() { jaroslav@1890: return getState(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: final int nonfairTryAcquireShared(int acquires) { jaroslav@1890: for (;;) { jaroslav@1890: int available = getState(); jaroslav@1890: int remaining = available - acquires; jaroslav@1890: if (remaining < 0 || jaroslav@1890: compareAndSetState(available, remaining)) jaroslav@1890: return remaining; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: protected final boolean tryReleaseShared(int releases) { jaroslav@1890: for (;;) { jaroslav@1890: int current = getState(); jaroslav@1890: int next = current + releases; jaroslav@1890: if (next < current) // overflow jaroslav@1890: throw new Error("Maximum permit count exceeded"); jaroslav@1890: if (compareAndSetState(current, next)) jaroslav@1890: return true; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: final void reducePermits(int reductions) { jaroslav@1890: for (;;) { jaroslav@1890: int current = getState(); jaroslav@1890: int next = current - reductions; jaroslav@1890: if (next > current) // underflow jaroslav@1890: throw new Error("Permit count underflow"); jaroslav@1890: if (compareAndSetState(current, next)) jaroslav@1890: return; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: final int drainPermits() { jaroslav@1890: for (;;) { jaroslav@1890: int current = getState(); jaroslav@1890: if (current == 0 || compareAndSetState(current, 0)) jaroslav@1890: return current; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * NonFair version jaroslav@1890: */ jaroslav@1890: static final class NonfairSync extends Sync { jaroslav@1890: private static final long serialVersionUID = -2694183684443567898L; jaroslav@1890: jaroslav@1890: NonfairSync(int permits) { jaroslav@1890: super(permits); jaroslav@1890: } jaroslav@1890: jaroslav@1890: protected int tryAcquireShared(int acquires) { jaroslav@1890: return nonfairTryAcquireShared(acquires); jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Fair version jaroslav@1890: */ jaroslav@1890: static final class FairSync extends Sync { jaroslav@1890: private static final long serialVersionUID = 2014338818796000944L; jaroslav@1890: jaroslav@1890: FairSync(int permits) { jaroslav@1890: super(permits); jaroslav@1890: } jaroslav@1890: jaroslav@1890: protected int tryAcquireShared(int acquires) { jaroslav@1890: for (;;) { jaroslav@1890: if (hasQueuedPredecessors()) jaroslav@1890: return -1; jaroslav@1890: int available = getState(); jaroslav@1890: int remaining = available - acquires; jaroslav@1890: if (remaining < 0 || jaroslav@1890: compareAndSetState(available, remaining)) jaroslav@1890: return remaining; jaroslav@1890: } jaroslav@1890: } jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a {@code Semaphore} with the given number of jaroslav@1890: * permits and nonfair fairness setting. jaroslav@1890: * jaroslav@1890: * @param permits the initial number of permits available. jaroslav@1890: * This value may be negative, in which case releases jaroslav@1890: * must occur before any acquires will be granted. jaroslav@1890: */ jaroslav@1890: public Semaphore(int permits) { jaroslav@1890: sync = new NonfairSync(permits); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Creates a {@code Semaphore} with the given number of jaroslav@1890: * permits and the given fairness setting. jaroslav@1890: * jaroslav@1890: * @param permits the initial number of permits available. jaroslav@1890: * This value may be negative, in which case releases jaroslav@1890: * must occur before any acquires will be granted. jaroslav@1890: * @param fair {@code true} if this semaphore will guarantee jaroslav@1890: * first-in first-out granting of permits under contention, jaroslav@1890: * else {@code false} jaroslav@1890: */ jaroslav@1890: public Semaphore(int permits, boolean fair) { jaroslav@1890: sync = fair ? new FairSync(permits) : new NonfairSync(permits); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires a permit from this semaphore, blocking until one is jaroslav@1890: * available, or the thread is {@linkplain Thread#interrupt interrupted}. jaroslav@1890: * jaroslav@1890: *

Acquires a permit, if one is available and returns immediately, jaroslav@1890: * reducing the number of available permits by one. jaroslav@1890: * jaroslav@1890: *

If no permit is available then the current thread becomes jaroslav@1890: * disabled for thread scheduling purposes and lies dormant until jaroslav@1890: * one of two things happens: jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: *

If the current thread: jaroslav@1890: *

jaroslav@1890: * then {@link InterruptedException} is thrown and the current thread's jaroslav@1890: * interrupted status is cleared. jaroslav@1890: * jaroslav@1890: * @throws InterruptedException if the current thread is interrupted jaroslav@1890: */ jaroslav@1890: public void acquire() throws InterruptedException { jaroslav@1890: sync.acquireSharedInterruptibly(1); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires a permit from this semaphore, blocking until one is jaroslav@1890: * available. jaroslav@1890: * jaroslav@1890: *

Acquires a permit, if one is available and returns immediately, jaroslav@1890: * reducing the number of available permits by one. jaroslav@1890: * jaroslav@1890: *

If no permit is available then the current thread becomes jaroslav@1890: * disabled for thread scheduling purposes and lies dormant until jaroslav@1890: * some other thread invokes the {@link #release} method for this jaroslav@1890: * semaphore and the current thread is next to be assigned a permit. jaroslav@1890: * jaroslav@1890: *

If the current thread is {@linkplain Thread#interrupt interrupted} jaroslav@1890: * while waiting for a permit then it will continue to wait, but the jaroslav@1890: * time at which the thread is assigned a permit may change compared to jaroslav@1890: * the time it would have received the permit had no interruption jaroslav@1890: * occurred. When the thread does return from this method its interrupt jaroslav@1890: * status will be set. jaroslav@1890: */ jaroslav@1890: public void acquireUninterruptibly() { jaroslav@1890: sync.acquireShared(1); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires a permit from this semaphore, only if one is available at the jaroslav@1890: * time of invocation. jaroslav@1890: * jaroslav@1890: *

Acquires a permit, if one is available and returns immediately, jaroslav@1890: * with the value {@code true}, jaroslav@1890: * reducing the number of available permits by one. jaroslav@1890: * jaroslav@1890: *

If no permit is available then this method will return jaroslav@1890: * immediately with the value {@code false}. jaroslav@1890: * jaroslav@1890: *

Even when this semaphore has been set to use a jaroslav@1890: * fair ordering policy, a call to {@code tryAcquire()} will jaroslav@1890: * immediately acquire a permit if one is available, whether or not jaroslav@1890: * other threads are currently waiting. jaroslav@1890: * This "barging" behavior can be useful in certain jaroslav@1890: * circumstances, even though it breaks fairness. If you want to honor jaroslav@1890: * the fairness setting, then use jaroslav@1890: * {@link #tryAcquire(long, TimeUnit) tryAcquire(0, TimeUnit.SECONDS) } jaroslav@1890: * which is almost equivalent (it also detects interruption). jaroslav@1890: * jaroslav@1890: * @return {@code true} if a permit was acquired and {@code false} jaroslav@1890: * otherwise jaroslav@1890: */ jaroslav@1890: public boolean tryAcquire() { jaroslav@1890: return sync.nonfairTryAcquireShared(1) >= 0; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires a permit from this semaphore, if one becomes available jaroslav@1890: * within the given waiting time and the current thread has not jaroslav@1890: * been {@linkplain Thread#interrupt interrupted}. jaroslav@1890: * jaroslav@1890: *

Acquires a permit, if one is available and returns immediately, jaroslav@1890: * with the value {@code true}, jaroslav@1890: * reducing the number of available permits by one. jaroslav@1890: * jaroslav@1890: *

If no permit is available then the current thread becomes jaroslav@1890: * disabled for thread scheduling purposes and lies dormant until jaroslav@1890: * one of three things happens: jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: *

If a permit is acquired then the value {@code true} is returned. jaroslav@1890: * jaroslav@1890: *

If the current thread: jaroslav@1890: *

jaroslav@1890: * then {@link InterruptedException} is thrown and the current thread's jaroslav@1890: * interrupted status is cleared. jaroslav@1890: * jaroslav@1890: *

If the specified waiting time elapses then the value {@code false} jaroslav@1890: * is returned. If the time is less than or equal to zero, the method jaroslav@1890: * will not wait at all. jaroslav@1890: * jaroslav@1890: * @param timeout the maximum time to wait for a permit jaroslav@1890: * @param unit the time unit of the {@code timeout} argument jaroslav@1890: * @return {@code true} if a permit was acquired and {@code false} jaroslav@1890: * if the waiting time elapsed before a permit was acquired jaroslav@1890: * @throws InterruptedException if the current thread is interrupted jaroslav@1890: */ jaroslav@1890: public boolean tryAcquire(long timeout, TimeUnit unit) jaroslav@1890: throws InterruptedException { jaroslav@1890: return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout)); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Releases a permit, returning it to the semaphore. jaroslav@1890: * jaroslav@1890: *

Releases a permit, increasing the number of available permits by jaroslav@1890: * one. If any threads are trying to acquire a permit, then one is jaroslav@1890: * selected and given the permit that was just released. That thread jaroslav@1890: * is (re)enabled for thread scheduling purposes. jaroslav@1890: * jaroslav@1890: *

There is no requirement that a thread that releases a permit must jaroslav@1890: * have acquired that permit by calling {@link #acquire}. jaroslav@1890: * Correct usage of a semaphore is established by programming convention jaroslav@1890: * in the application. jaroslav@1890: */ jaroslav@1890: public void release() { jaroslav@1890: sync.releaseShared(1); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires the given number of permits from this semaphore, jaroslav@1890: * blocking until all are available, jaroslav@1890: * or the thread is {@linkplain Thread#interrupt interrupted}. jaroslav@1890: * jaroslav@1890: *

Acquires the given number of permits, if they are available, jaroslav@1890: * and returns immediately, reducing the number of available permits jaroslav@1890: * by the given amount. jaroslav@1890: * jaroslav@1890: *

If insufficient permits are available then the current thread becomes jaroslav@1890: * disabled for thread scheduling purposes and lies dormant until jaroslav@1890: * one of two things happens: jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: *

If the current thread: jaroslav@1890: *

jaroslav@1890: * then {@link InterruptedException} is thrown and the current thread's jaroslav@1890: * interrupted status is cleared. jaroslav@1890: * Any permits that were to be assigned to this thread are instead jaroslav@1890: * assigned to other threads trying to acquire permits, as if jaroslav@1890: * permits had been made available by a call to {@link #release()}. jaroslav@1890: * jaroslav@1890: * @param permits the number of permits to acquire jaroslav@1890: * @throws InterruptedException if the current thread is interrupted jaroslav@1890: * @throws IllegalArgumentException if {@code permits} is negative jaroslav@1890: */ jaroslav@1890: public void acquire(int permits) throws InterruptedException { jaroslav@1890: if (permits < 0) throw new IllegalArgumentException(); jaroslav@1890: sync.acquireSharedInterruptibly(permits); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires the given number of permits from this semaphore, jaroslav@1890: * blocking until all are available. jaroslav@1890: * jaroslav@1890: *

Acquires the given number of permits, if they are available, jaroslav@1890: * and returns immediately, reducing the number of available permits jaroslav@1890: * by the given amount. jaroslav@1890: * jaroslav@1890: *

If insufficient permits are available then the current thread becomes jaroslav@1890: * disabled for thread scheduling purposes and lies dormant until jaroslav@1890: * some other thread invokes one of the {@link #release() release} jaroslav@1890: * methods for this semaphore, the current thread is next to be assigned jaroslav@1890: * permits and the number of available permits satisfies this request. jaroslav@1890: * jaroslav@1890: *

If the current thread is {@linkplain Thread#interrupt interrupted} jaroslav@1890: * while waiting for permits then it will continue to wait and its jaroslav@1890: * position in the queue is not affected. When the thread does return jaroslav@1890: * from this method its interrupt status will be set. jaroslav@1890: * jaroslav@1890: * @param permits the number of permits to acquire jaroslav@1890: * @throws IllegalArgumentException if {@code permits} is negative jaroslav@1890: * jaroslav@1890: */ jaroslav@1890: public void acquireUninterruptibly(int permits) { jaroslav@1890: if (permits < 0) throw new IllegalArgumentException(); jaroslav@1890: sync.acquireShared(permits); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires the given number of permits from this semaphore, only jaroslav@1890: * if all are available at the time of invocation. jaroslav@1890: * jaroslav@1890: *

Acquires the given number of permits, if they are available, and jaroslav@1890: * returns immediately, with the value {@code true}, jaroslav@1890: * reducing the number of available permits by the given amount. jaroslav@1890: * jaroslav@1890: *

If insufficient permits are available then this method will return jaroslav@1890: * immediately with the value {@code false} and the number of available jaroslav@1890: * permits is unchanged. jaroslav@1890: * jaroslav@1890: *

Even when this semaphore has been set to use a fair ordering jaroslav@1890: * policy, a call to {@code tryAcquire} will jaroslav@1890: * immediately acquire a permit if one is available, whether or jaroslav@1890: * not other threads are currently waiting. This jaroslav@1890: * "barging" behavior can be useful in certain jaroslav@1890: * circumstances, even though it breaks fairness. If you want to jaroslav@1890: * honor the fairness setting, then use {@link #tryAcquire(int, jaroslav@1890: * long, TimeUnit) tryAcquire(permits, 0, TimeUnit.SECONDS) } jaroslav@1890: * which is almost equivalent (it also detects interruption). jaroslav@1890: * jaroslav@1890: * @param permits the number of permits to acquire jaroslav@1890: * @return {@code true} if the permits were acquired and jaroslav@1890: * {@code false} otherwise jaroslav@1890: * @throws IllegalArgumentException if {@code permits} is negative jaroslav@1890: */ jaroslav@1890: public boolean tryAcquire(int permits) { jaroslav@1890: if (permits < 0) throw new IllegalArgumentException(); jaroslav@1890: return sync.nonfairTryAcquireShared(permits) >= 0; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires the given number of permits from this semaphore, if all jaroslav@1890: * become available within the given waiting time and the current jaroslav@1890: * thread has not been {@linkplain Thread#interrupt interrupted}. jaroslav@1890: * jaroslav@1890: *

Acquires the given number of permits, if they are available and jaroslav@1890: * returns immediately, with the value {@code true}, jaroslav@1890: * reducing the number of available permits by the given amount. jaroslav@1890: * jaroslav@1890: *

If insufficient permits are available then jaroslav@1890: * the current thread becomes disabled for thread scheduling jaroslav@1890: * purposes and lies dormant until one of three things happens: jaroslav@1890: *

jaroslav@1890: * jaroslav@1890: *

If the permits are acquired then the value {@code true} is returned. jaroslav@1890: * jaroslav@1890: *

If the current thread: jaroslav@1890: *

jaroslav@1890: * then {@link InterruptedException} is thrown and the current thread's jaroslav@1890: * interrupted status is cleared. jaroslav@1890: * Any permits that were to be assigned to this thread, are instead jaroslav@1890: * assigned to other threads trying to acquire permits, as if jaroslav@1890: * the permits had been made available by a call to {@link #release()}. jaroslav@1890: * jaroslav@1890: *

If the specified waiting time elapses then the value {@code false} jaroslav@1890: * is returned. If the time is less than or equal to zero, the method jaroslav@1890: * will not wait at all. Any permits that were to be assigned to this jaroslav@1890: * thread, are instead assigned to other threads trying to acquire jaroslav@1890: * permits, as if the permits had been made available by a call to jaroslav@1890: * {@link #release()}. jaroslav@1890: * jaroslav@1890: * @param permits the number of permits to acquire jaroslav@1890: * @param timeout the maximum time to wait for the permits jaroslav@1890: * @param unit the time unit of the {@code timeout} argument jaroslav@1890: * @return {@code true} if all permits were acquired and {@code false} jaroslav@1890: * if the waiting time elapsed before all permits were acquired jaroslav@1890: * @throws InterruptedException if the current thread is interrupted jaroslav@1890: * @throws IllegalArgumentException if {@code permits} is negative jaroslav@1890: */ jaroslav@1890: public boolean tryAcquire(int permits, long timeout, TimeUnit unit) jaroslav@1890: throws InterruptedException { jaroslav@1890: if (permits < 0) throw new IllegalArgumentException(); jaroslav@1890: return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout)); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Releases the given number of permits, returning them to the semaphore. jaroslav@1890: * jaroslav@1890: *

Releases the given number of permits, increasing the number of jaroslav@1890: * available permits by that amount. jaroslav@1890: * If any threads are trying to acquire permits, then one jaroslav@1890: * is selected and given the permits that were just released. jaroslav@1890: * If the number of available permits satisfies that thread's request jaroslav@1890: * then that thread is (re)enabled for thread scheduling purposes; jaroslav@1890: * otherwise the thread will wait until sufficient permits are available. jaroslav@1890: * If there are still permits available jaroslav@1890: * after this thread's request has been satisfied, then those permits jaroslav@1890: * are assigned in turn to other threads trying to acquire permits. jaroslav@1890: * jaroslav@1890: *

There is no requirement that a thread that releases a permit must jaroslav@1890: * have acquired that permit by calling {@link Semaphore#acquire acquire}. jaroslav@1890: * Correct usage of a semaphore is established by programming convention jaroslav@1890: * in the application. jaroslav@1890: * jaroslav@1890: * @param permits the number of permits to release jaroslav@1890: * @throws IllegalArgumentException if {@code permits} is negative jaroslav@1890: */ jaroslav@1890: public void release(int permits) { jaroslav@1890: if (permits < 0) throw new IllegalArgumentException(); jaroslav@1890: sync.releaseShared(permits); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns the current number of permits available in this semaphore. jaroslav@1890: * jaroslav@1890: *

This method is typically used for debugging and testing purposes. jaroslav@1890: * jaroslav@1890: * @return the number of permits available in this semaphore jaroslav@1890: */ jaroslav@1890: public int availablePermits() { jaroslav@1890: return sync.getPermits(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Acquires and returns all permits that are immediately available. jaroslav@1890: * jaroslav@1890: * @return the number of permits acquired jaroslav@1890: */ jaroslav@1890: public int drainPermits() { jaroslav@1890: return sync.drainPermits(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Shrinks the number of available permits by the indicated jaroslav@1890: * reduction. This method can be useful in subclasses that use jaroslav@1890: * semaphores to track resources that become unavailable. This jaroslav@1890: * method differs from {@code acquire} in that it does not block jaroslav@1890: * waiting for permits to become available. jaroslav@1890: * jaroslav@1890: * @param reduction the number of permits to remove jaroslav@1890: * @throws IllegalArgumentException if {@code reduction} is negative jaroslav@1890: */ jaroslav@1890: protected void reducePermits(int reduction) { jaroslav@1890: if (reduction < 0) throw new IllegalArgumentException(); jaroslav@1890: sync.reducePermits(reduction); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns {@code true} if this semaphore has fairness set true. jaroslav@1890: * jaroslav@1890: * @return {@code true} if this semaphore has fairness set true jaroslav@1890: */ jaroslav@1890: public boolean isFair() { jaroslav@1890: return sync instanceof FairSync; jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Queries whether any threads are waiting to acquire. Note that jaroslav@1890: * because cancellations may occur at any time, a {@code true} jaroslav@1890: * return does not guarantee that any other thread will ever jaroslav@1890: * acquire. This method is designed primarily for use in jaroslav@1890: * monitoring of the system state. jaroslav@1890: * jaroslav@1890: * @return {@code true} if there may be other threads waiting to jaroslav@1890: * acquire the lock jaroslav@1890: */ jaroslav@1890: public final boolean hasQueuedThreads() { jaroslav@1890: return sync.hasQueuedThreads(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns an estimate of the number of threads waiting to acquire. jaroslav@1890: * The value is only an estimate because the number of threads may jaroslav@1890: * change dynamically while this method traverses internal data jaroslav@1890: * structures. This method is designed for use in monitoring of the jaroslav@1890: * system state, not for synchronization control. jaroslav@1890: * jaroslav@1890: * @return the estimated number of threads waiting for this lock jaroslav@1890: */ jaroslav@1890: public final int getQueueLength() { jaroslav@1890: return sync.getQueueLength(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns a collection containing threads that may be waiting to acquire. jaroslav@1890: * Because the actual set of threads may change dynamically while jaroslav@1890: * constructing this result, the returned collection is only a best-effort jaroslav@1890: * estimate. The elements of the returned collection are in no particular jaroslav@1890: * order. This method is designed to facilitate construction of jaroslav@1890: * subclasses that provide more extensive monitoring facilities. jaroslav@1890: * jaroslav@1890: * @return the collection of threads jaroslav@1890: */ jaroslav@1890: protected Collection getQueuedThreads() { jaroslav@1890: return sync.getQueuedThreads(); jaroslav@1890: } jaroslav@1890: jaroslav@1890: /** jaroslav@1890: * Returns a string identifying this semaphore, as well as its state. jaroslav@1890: * The state, in brackets, includes the String {@code "Permits ="} jaroslav@1890: * followed by the number of permits. jaroslav@1890: * jaroslav@1890: * @return a string identifying this semaphore, as well as its state jaroslav@1890: */ jaroslav@1890: public String toString() { jaroslav@1890: return super.toString() + "[Permits = " + sync.getPermits() + "]"; jaroslav@1890: } jaroslav@1890: }