Semaphore 介绍
Semaphore是一个计数信号量,Semaphore中保留多个令牌,每一个acquire都会阻塞直到获取一个可用的令牌。每一个release都会归还一个持有的令牌,这也意味着,其他的acquire可以获得该令牌继续执行。
但是Semaphore并不是真正的拥有令牌,而是通过一个计数器实现的。
Semaphores通常用在多个线程想要获取相同的资源。控制该资源的接入量(限流控制)
主要方法介绍
public Semaphore(int permits);//构造方法,设置许可令牌的数量,默认为非公平锁
public Semaphore(int permits, boolean fair);//构造方法,设置许可令牌的数量,指定是否采用公平锁策略
public void acquire() throws InterruptedException;尝试获取一个令牌,可被中断
public void acquire(int permits) throws InterruptedException;尝试获取多个令牌,可被中断
public void acquireUninterruptibly();//尝试获取一个令牌,不可被中断
public void acquireUninterruptibly(int permits);//尝试获取多个令牌,不可被中断
public int availablePermits();//获取剩余可用令牌的数量
public int drainPermits();//获取剩余的所有令牌,返回可用的令牌数量
public final int getQueueLength();//获取阻塞等待可用令牌的线程数
public final boolean hasQueuedThreads();//判断是阻塞队列中是否有等待线程
public boolean tryAcquire();//尝试获取一个令牌,返回获取成功或失败
public boolean tryAcquire(int permits);//尝试获取多个令牌,返回获取成功或失败
public boolean tryAcquire(long timeout, TimeUnit unit) throws InterruptedException;//在指定的时间内尝试获取一个令牌,返回成功或失败
public boolean tryAcquire(int permits, long timeout, TimeUnit unit) throws InterruptedException;//在指定的时间内尝试获取permits个令牌,返回获取成功或失败
public boolean isFair();//判断公平策略
关键方法实现代码分析
1. acquire()源码分析
/**
* 从Semaphore中获取一个令牌,阻塞直到有令牌可用或线程被中断
* 如果有令牌可用,那么立即返回,并且减少可用令牌的数量
* /
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
/**
* 已可中断的方式获取共享锁,首先判断线程的中断状态,然后至少调用一次
* tryAcquireShared(获取共享锁成功)。否则线程会被加入到AQS队列中,
* 可能会重复执行阻塞和运行,调用tryAcquireShared直到获取共享锁成功或线程被中断。
* /
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//尝试获取共享锁,根据构造Semaphore时传入的公平策略,分为公平和非公平
//如果获取共享锁失败,则会将当前线程加入到AQS队列中,直到获取成功或被中断
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
abstract static class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 1192457210091910933L;
//初始化许可令牌的数量
Sync(int permits) {
setState(permits);
}
//获取许可令牌的数量
final int getPermits() {
return getState();
}
//非公平策略尝试获取共享锁,如果可用令牌数不够,则返回负数,会将当前线程加入到AQS队列
final int nonfairTryAcquireShared(int acquires) {
for (;;) {
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
//通过自旋释放共享锁,即增加池中令牌数量(releases)
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");
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;
}
}
//将池中所有可用的令牌数量归零
final int drainPermits() {
for (;;) {
int current = getState();
if (current == 0 || compareAndSetState(current, 0))
return current;
}
}
}
/**
* 非公平锁,在进入AQS队列前尝试获取锁
*/
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);
}
}
/**
* 公平锁,将线程加入到AQS队列中,根据进入AQS队列的先后顺序获取锁(FIFO)
*/
static final class FairSync extends Sync {
private static final long serialVersionUID = 2014338818796000944L;
//公平锁初始化许可令牌数
FairSync(int permits) {
super(permits);
}
//尝试获取公平锁
protected int tryAcquireShared(int acquires) {
for (;;) {
//判断AQS队列中是否有前驱(等待获取令牌的线程),如果有,则获取公平锁失败
//如果AQS队列中没有等待获取令牌的线程节点,则尝试获取令牌
if (hasQueuedPredecessors())
return -1;
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
}
/**
* 获取共享锁,这部分代码在CountDownLatch中已经分析过,此处不再分析参考
* /
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);
}
}
2. release()源码分析
/**
* 释放令牌,将其归还给Semaphore
* /
public void release() {
sync.releaseShared(1);
}
/**
* 释放归还令牌,如果释放成功,会触发AQS队列中的线程重新获取令牌
* /
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
//该部分代码在CountDownLatch中已经分析
doReleaseShared();
return true;
}
return false;
}