Semaphore详解

阅读更多
AtomicInteger解析: http://donald-draper.iteye.com/blog/2359555
锁持有者管理器AbstractOwnableSynchronizer: http://donald-draper.iteye.com/blog/2360109
AQS线程挂起辅助类LockSupport: http://donald-draper.iteye.com/blog/2360206
AQS详解-CLH队列,线程等待状态: http://donald-draper.iteye.com/blog/2360256
AQS-Condition详解: http://donald-draper.iteye.com/blog/2360381
可重入锁ReentrantLock详解: http://donald-draper.iteye.com/blog/2360411
CountDownLatch使用场景: http://donald-draper.iteye.com/blog/2348106
CountDownLatch详解: http://donald-draper.iteye.com/blog/2360597
CyclicBarrier详解: http://donald-draper.iteye.com/blog/2360812
/*
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Written by Doug Lea with assistance from members of JCP JSR-166
 * Expert Group and released to the public domain, as explained at
 * http://creativecommons.org/publicdomain/zero/1.0/
 */

package java.util.concurrent;
import java.util.*;
import java.util.concurrent.locks.*;
import java.util.concurrent.atomic.*;

/**
 * A counting semaphore.  Conceptually, a semaphore maintains a set of
 * permits.  Each {@link #acquire} blocks if necessary until a permit is
 * available, and then takes it.  Each {@link #release} adds a permit,
 * potentially releasing a blocking acquirer.
 * However, no actual permit objects are used; the {@code Semaphore} just
 * keeps a count of the number available and acts accordingly.
 *
 一个计算的信号量,维持着一个许可集。如果许可集中,无许可,线程acquire,
 将会阻塞,直到其他线程释放许可。线程每一次释放#release,则添加一个许可,潜在地
 释放一个阻塞信号获取者。信号量的许可,实际上并不是一对象,仅仅保证一定数量的虚拟许可证。
 * 

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

 信号量经常被用于,只有一定数量的线程访问一些物理或逻辑资源。比如用信号量控制池对象的获取。
 * class Pool {
 *   private static final int MAX_AVAILABLE = 100;
 *   private final Semaphore available = new Semaphore(MAX_AVAILABLE, true);
 *
 *   public Object getItem() throws InterruptedException {
 *     available.acquire();
 *     return getNextAvailableItem();
 *   }
 *
 *   public void putItem(Object x) {
 *     if (markAsUnused(x))
 *       available.release();
 *   }
 *
 *   // Not a particularly efficient data structure; just for demo
 *
 *   protected Object[] items = ... whatever kinds of items being managed
 *   protected boolean[] used = new boolean[MAX_AVAILABLE];
 *
 *   protected synchronized Object getNextAvailableItem() {
 *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
 *       if (!used[i]) {
 *          used[i] = true;
 *          return items[i];
 *       }
 *     }
 *     return null; // not reached
 *   }
 *
 *   protected synchronized boolean markAsUnused(Object item) {
 *     for (int i = 0; i < MAX_AVAILABLE; ++i) {
 *       if (item == items[i]) {
 *          if (used[i]) {
 *            used[i] = false;
 *            return true;
 *          } else
 *            return false;
 *       }
 *     }
 *     return false;
 *   }
 *
 * }
 * 
* *

Before obtaining an item each thread must acquire a permit from * the semaphore, guaranteeing that an item is available for use. When * the thread has finished with the item it is returned back to the * pool and a permit is returned to the semaphore, allowing another * thread to acquire that item. Note that no synchronization lock is * held when {@link #acquire} is called as that would prevent an item * from being returned to the pool. The semaphore encapsulates the * synchronization needed to restrict access to the pool, separately * from any synchronization needed to maintain the consistency of the * pool itself. * 在线程从对象池,获取对象前,必须从信号量获取许可,用于保证对象时可利用的。 当线程任务完成时,对象将会被放回池中,释放许可,同时允许其他线程获取对象。 如果线程acquire,但没有持有同步锁,则对象将返回池中。信号量中的同步器需要严格的 控制对象池的访问,与其他维持对象池一致性的同步器相互独立。 *

A semaphore initialized to one, and which is used such that it * only has at most one permit available, can serve as a mutual * exclusion lock. This is more commonly known as a [i]binary * semaphore[/i], because it only has two states: one permit * available, or zero permits available. When used in this way, the * binary semaphore has the property (unlike many {@link Lock} * implementations), that the "lock" can be released by a * thread other than the owner (as semaphores have no notion of * ownership). This can be useful in some specialized contexts, such * as deadlock recovery. * 当信号量被初始化为1时,作为互斥锁,可以用于最多只有一个 permit可以用的场景。 这种方式比较有名的一种是二进制信号量,因为它只有两种状态,1表示可利用,0表示 无permits可利用。二进制信号量,有一个属性,锁可以被其他非持有锁的线程释放。 这种特性在一些特殊的上下文场景中,比较拥有,比如恢复死锁。 *

The constructor for this class optionally accepts a * [i]fairness[/i] parameter. When set false, this class makes no * guarantees about the order in which threads acquire permits. In * particular, [i]barging[/i] is permitted, that is, a thread * invoking {@link #acquire} can be allocated a permit ahead of a * thread that has been waiting - logically the new thread places itself at * the head of the queue of waiting threads. When fairness is set true, the * semaphore guarantees that threads invoking any of the {@link * #acquire() acquire} methods are selected to obtain permits in the order in * which their invocation of those methods was processed * (first-in-first-out; FIFO). Note that FIFO ordering necessarily * applies to specific internal points of execution within these * methods. So, it is possible for one thread to invoke * {@code acquire} before another, but reach the ordering point after * the other, and similarly upon return from the method. * Also note that the untimed {@link #tryAcquire() tryAcquire} methods do not * honor the fairness setting, but will take any permits that are * available. * 信号量的构造函数,中带一个公平性参数。当设置为false时,信号量不能够保证,线程 能够按顺序获取许可。在特殊情况下,barging是允许的,由于一个新线程将自己放在队列的 头部,当调用acquire时,可能会在已经等待线程,前面获取许可。当为公平true时, 信号量保证,线程按照,他们获取信号的顺序,给予许可。FIFO队列中,并不能保证却对的 顺序,一个线程可能调用获取信号量,在另一线程前面,但另一个线程先到达顺序点。 tryAcquire方法,不能保证绝对的公平性, 当许可可利用,则许可将被分配。 *

Generally, semaphores used to control resource access should be * initialized as fair, to ensure that no thread is starved out from * accessing a resource. When using semaphores for other kinds of * synchronization control, the throughput advantages of non-fair * ordering often outweigh fairness considerations. * 信号量,用于控制资源的访问时,应该初始化为公平锁,以保证不会有线程,几乎 访问不到资源。当信号量用于其他场景时,非公平锁,可以提高吞吐量。 *

This class also provides convenience methods to {@link * #acquire(int) acquire} and {@link #release(int) release} multiple * permits at a time. Beware of the increased risk of indefinite * postponement when these methods are used without fairness set true. 信号量允许一次获取或释放多个信号量。当这些方法以非公平锁的方式使用,将会 增加不确定性的风险 * *

Memory consistency effects: Actions in a thread prior to calling * a "release" method such as {@code release()} * [url=package-summary.html#MemoryVisibility]happen-before[/url] * actions following a successful "acquire" method such as {@code acquire()} * in another thread. * 内存一致性:一个线程释放锁动作,发生在另一个线程成功获取锁的前面。 * @since 1.5 * @author Doug Lea * */ public class Semaphore implements java.io.Serializable { private static final long serialVersionUID = -3222578661600680210L; /** All mechanics via AbstractQueuedSynchronizer subclass */ //内部同步锁,基于AQS实现 private final Sync sync; /** * Synchronization implementation for semaphore. Uses AQS state * to represent permits. Subclassed into fair and nonfair * versions. */ abstract static class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 1192457210091910933L; //以锁的状态来,来存储许可 Sync(int permits) { setState(permits); } final int getPermits() { return getState(); } //非公平方式获取锁 final int nonfairTryAcquireShared(int acquires) { for (;;) { int available = getState(); int remaining = available - acquires; //如果,无许可可用,则返回,有,则CAS更新锁状态 if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } } //释放共享锁 protected final boolean tryReleaseShared(int releases) { for (;;) { //释放的信号量,不能大于当前可用许可 int current = getState(); int next = current + releases; if (next < current) // overflow throw new Error("Maximum permit count exceeded"); //CAS更新锁状态 if (compareAndSetState(current, next)) return true; } } //减少当前可用的许可 final void reducePermits(int reductions) { for (;;) { int current = getState(); int next = current - reductions; if (next > current) // underflow throw new Error("Permit count underflow"); if (compareAndSetState(current, next)) return; } } /** * Acquires and returns all permits that are immediately available. *获取返回当前以及可用的许可 * @return the number of permits acquired */ final int drainPermits() { for (;;) { int current = getState(); if (current == 0 || compareAndSetState(current, 0)) return current; } } } /** * NonFair version,非公平锁 */ static final class NonfairSync extends Sync { private static final long serialVersionUID = -2694183684443567898L; NonfairSync(int permits) { super(permits); } protected int tryAcquireShared(int acquires) { return nonfairTryAcquireShared(acquires); } } /** * Fair version,公平锁 */ static final class FairSync extends Sync { private static final long serialVersionUID = 2014338818796000944L; FairSync(int permits) { super(permits); } protected int tryAcquireShared(int acquires) { for (;;) { //先看有没有前驱,有则返回,获取信号失败,没有前驱,则尝试获取信号锁 if (hasQueuedPredecessors()) return -1; int available = getState(); int remaining = available - acquires; if (remaining < 0 || compareAndSetState(available, remaining)) return remaining; } } } //默认为非公平锁,许可必须为正值 public Semaphore(int permits) { sync = new NonfairSync(permits); } //带公平性参数的信号量,构造 public Semaphore(int permits, boolean fair) { sync = fair ? new FairSync(permits) : new NonfairSync(permits); } }


尝试获取锁,可中断
public void acquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
    }

//AQS
public final void acquireSharedInterruptibly(int arg)
            throws InterruptedException {
        if (Thread.interrupted())
	    //如果中断,则抛出中断异常
            throw new InterruptedException();
	    //如果获取失败,则自旋
        if (tryAcquireShared(arg) < 0)
            doAcquireSharedInterruptibly(arg);
    }
//待子类扩展
 protected int tryAcquireShared(int arg) {
        throw new UnsupportedOperationException();
    }

tryAcquireShared放在AQS中为空体,实际为信号量中的内部SYNC中的方法,上面
我们已经看过。这个方法我们在前面有说过,这里简单说一下,当尝试获取锁,失败,添加到等待队列自旋等待,尝试获取锁。
//AQS
 private void doAcquireSharedInterruptibly(int arg)
        throws InterruptedException {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    throw new InterruptedException();
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }

以不可中断方式,获取共享锁
public void acquireUninterruptibly() {
        sync.acquireShared(1);
    }

//AQS
 
 /**
     * Acquires in shared uninterruptible mode.
     * @param arg the acquire argument
     */
已共享非中断模式,获取锁
 public final void acquireShared(int arg) {
        if (tryAcquireShared(arg) < 0)
            doAcquireShared(arg);
    }
      private void doAcquireShared(int arg) {
        final Node node = addWaiter(Node.SHARED);
        boolean failed = true;
        try {
            boolean interrupted = false;
            for (;;) {
                final Node p = node.predecessor();
                if (p == head) {
                    int r = tryAcquireShared(arg);
                    if (r >= 0) {
                        setHeadAndPropagate(node, r);
                        p.next = null; // help GC
                        if (interrupted)
			    //关键在这,如果中断,则自中断,消除中断位
                            selfInterrupt();
                        failed = false;
                        return;
                    }
                }
                if (shouldParkAfterFailedAcquire(p, node) &&
                    parkAndCheckInterrupt())
                    interrupted = true;
            }
        } finally {
            if (failed)
                cancelAcquire(node);
        }
    }
  /**
     * Convenience method to interrupt current thread.
     */
    private static void selfInterrupt() {
        Thread.currentThread().interrupt();
    }

//Semaphore
尝试获取锁时,是以非公平的方式,抢占锁
 
  public boolean tryAcquire() {
        return sync.nonfairTryAcquireShared(1) >= 0;
    }

尝试获取共享锁,当超时,还没有获取锁,则取消锁的获取
 public boolean tryAcquire(long timeout, TimeUnit unit)
        throws InterruptedException {
        return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
    }

以可中断方式,获取permits个许可
 public void acquire(int permits) throws InterruptedException {
        if (permits < 0) throw new IllegalArgumentException();
        sync.acquireSharedInterruptibly(permits);
    }

以非可中断方式,获取permits个许可
public void acquireUninterruptibly(int permits) {
        if (permits < 0) throw new IllegalArgumentException();
        sync.acquireShared(permits);
    }

以非公平方式,尝试获取permits个许可
public boolean tryAcquire(int permits) {
        if (permits < 0) throw new IllegalArgumentException();
        return sync.nonfairTryAcquireShared(permits) >= 0;
    }

尝试获取permits个许可,当超时,还没有获取锁,则取消锁的获取
  public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
        throws InterruptedException {
        if (permits < 0) throw new IllegalArgumentException();
        return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
    }

//释放锁
 public void release() {
        sync.releaseShared(1);
    }

//AQS
 public final boolean releaseShared(int arg) {
        if (tryReleaseShared(arg)) {
            doReleaseShared();
            return true;
        }
        return false;
    }
//唤醒后继节点线程
  * Release action for shared mode -- signal successor and ensure
     * propagation. (Note: For exclusive mode, release just amounts
     * to calling unparkSuccessor of head if it needs signal.)
     */
    private void doReleaseShared() {
        /*
         * Ensure that a release propagates, even if there are other
         * in-progress acquires/releases.  This proceeds in the usual
         * way of trying to unparkSuccessor of head if it needs
         * signal. But if it does not, status is set to PROPAGATE to
         * ensure that upon release, propagation continues.
         * Additionally, we must loop in case a new node is added
         * while we are doing this. Also, unlike other uses of
         * unparkSuccessor, we need to know if CAS to reset status
         * fails, if so rechecking.
         */
        for (;;) {
            Node h = head;
            if (h != null && h != tail) {
                int ws = h.waitStatus;
                if (ws == Node.SIGNAL) {
                    if (!compareAndSetWaitStatus(h, Node.SIGNAL, 0))
                        continue;            // loop to recheck cases
                    unparkSuccessor(h);
                }
                else if (ws == 0 &&
                         !compareAndSetWaitStatus(h, 0, Node.PROPAGATE))
                    continue;                // loop on failed CAS
            }
            if (h == head)                   // loop if head changed
                break;
        }
    }

//Semaphore
//释放permits个许可
 public void release(int permits) {
        if (permits < 0) throw new IllegalArgumentException();
        sync.releaseShared(permits);
    }
  /**
     * Returns the current number of permits available in this semaphore.
     *
     * 

This method is typically used for debugging and testing purposes. * * @return the number of permits available in this semaphore */ //当前可用许可 public int availablePermits() { return sync.getPermits(); } /** * Acquires and returns all permits that are immediately available. *获取返回当前以及可用的许可 * @return the number of permits acquired */ public int drainPermits() { return sync.drainPermits(); } /** * Shrinks the number of available permits by the indicated * reduction. This method can be useful in subclasses that use * semaphores to track resources that become unavailable. This * method differs from {@code acquire} in that it does not block * waiting for permits to become available. * 减少当前可用的许可,这个方法在子类想要用信号量,追踪资源是否可用是 非常有用,此方法不会阻塞。 * @param reduction the number of permits to remove * @throws IllegalArgumentException if {@code reduction} is negative */ protected void reducePermits(int reduction) { if (reduction < 0) throw new IllegalArgumentException(); sync.reducePermits(reduction); } /** * Returns {@code true} if this semaphore has fairness set true. * * @return {@code true} if this semaphore has fairness set true */ public boolean isFair() { return sync instanceof FairSync; } /** * Queries whether any threads are waiting to acquire. Note that * because cancellations may occur at any time, a {@code true} * return does not guarantee that any other thread will ever * acquire. This method is designed primarily for use in * monitoring of the system state. * * @return {@code true} if there may be other threads waiting to * acquire the lock */ public final boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } /** * Returns an estimate of the number of threads waiting to acquire. * The value is only an estimate because the number of threads may * change dynamically while this method traverses internal data * structures. This method is designed for use in monitoring of the * system state, not for synchronization control. * * @return the estimated number of threads waiting for this lock */ public final int getQueueLength() { return sync.getQueueLength(); } /** * Returns a collection containing threads that may be waiting to acquire. * Because the actual set of threads may change dynamically while * constructing this result, the returned collection is only a best-effort * estimate. The elements of the returned collection are in no particular * order. This method is designed to facilitate construction of * subclasses that provide more extensive monitoring facilities. * * @return the collection of threads */ protected Collection getQueuedThreads() { return sync.getQueuedThreads(); }


总结:

信号量,维持着一个许可集。如果许可集中,无许可,线程acquire,
将会阻塞,直到其他线程释放许可。线程每一次释放#release,则添加一个许可,潜在地
释放一个阻塞信号获取者。信号量的许可,实际上并不是一对象,仅仅保证一定数量的虚拟许可证。信号量经常被用于,只有一定数量的线程访问一些物理或逻辑资源。比如用信号量控制池对象的获取。当信号量被初始化为1时,作为互斥锁,可以用于最多只有一个 permit可以用的场景。这种方式比较有名的一种是二进制信号量,因为它只有两种状态,1表示可利用,0表示无permits可利用。二进制信号量,有一个属性,锁可以被其他非持有锁的线程释放。
这种特性在一些特殊的上下文场景中,比较拥有,比如恢复死锁。信号量中的锁有公平和非公平方式,这个和我们前面讲的可重入锁,有点相似。非公平方式,获取锁,首先检查锁是否可用,可用则获取,公平锁获取锁,先检查有没有前驱节点,有则等待,没有则获取。获取锁的方法,有多种,有公平的和非公平,则个要看需求。

你可能感兴趣的:(java,juc)