Semaphore阅读笔记
一、简介
Semaphore,信号量,它保存了一系列的许可(permits),每次调用acquire()都讲消耗一个许可,每次调用release()都讲归还一个许可。
场景:
- 通常用于限制同一时间对共享资源的访问次数上,也就是我们常说的限流。
二、继承关系图
三、存储结构
内部包含了实现了一个AQS的同步器Sync,他有两个子类,一个共FairSync和NonFairSynch。说明Semaphore也是区分公平模式和非公平模式
主要属性 state,也称为permits许可,每次释放会增加许可,获取锁会减少许可
四、源码分析
内部类
Sync
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;//减去这次获取的许可,还剩几次
//如果剩余许可小于0 就直接返回剩余许可
//如果剩余许可大于等于0 就尝试更新statez值,成功了返回剩余许可
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,增加后还小于当前state则抛异常
throw new Error("Maximum permit count exceeded");
if (compareAndSetState(current, next))//原子更新state
return true;
}
}
/** 减少许可 */
final void reducePermits(int reductions) {
for (;;) {
int current = getState();
int next = current - reductions;//减少后的剩余许可
if (next > current) // underflow,减少后大于当前state则抛异常
throw new Error("Permit count underflow");
if (compareAndSetState(current, next))//原子更新state
return;
}
}
/** 销毁许可 */
final int drainPermits() {
for (;;) {
int current = getState();
// 如果为0,直接返回
// 如果不为0 ,就原子更新state为0
if (current == 0 || compareAndSetState(current, 0))
return current;
}
}
}
NonFairSync
static final class NonfairSync extends Sync {
private static final long serialVersionUID = -2694183684443567898L;
/** 构造方法,调用父类的构造器 */
NonfairSync(int permits) {
super(permits);
}
/** 尝试获取许可,直接调用的Sync.nonfairTryAcquireShared()父类的 */
protected int tryAcquireShared(int acquires) {
return nonfairTryAcquireShared(acquires);
}
}
FairSync
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;
// 没有排队的再尝试更新state的值,如果获取许可后的剩余许可小于0 则返回剩余许可数量
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
}
属性
private final Sync sync; // 由Semphore的构造器实例化同步器
构造
/** 默认构造,创建时传入许可次数,默认使用给公平 */
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
/** 构造方法,需要传入许可次数,及是否公平模式 */
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
主要方法
/** 获取一个许可 ,默认使用的是 可中断方式,如果尝试获取失败,会进入AQS的队列排队*/
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
/** 获取一个许可,非中断方式,如果尝试获取许可失败,会进入AQS的队列排队 */
public void acquireUninterruptibly() {
sync.acquireShared(1);
}
/** 尝试获取一个许可,获取后剩余许可小于 0 则返回false,否则true */
public boolean tryAcquire() {
return sync.nonfairTryAcquireShared(1) >= 0;
}
/** 尝试获取一个许可,先尝试一次获取许可,如果失败则会等待timeout时间,这段时间内都没有获取许可,则返回false且加入AQS队列,否则返回true */
public boolean tryAcquire(long timeout, TimeUnit unit)
throws InterruptedException {
return sync.tryAcquireSharedNanos(1, unit.toNanos(timeout));
}
/** 释放一个许可,释放一个许可时 state值会加1,并会唤醒下一个等待许可的线程 */
public void release() {
sync.releaseShared(1);
}
/** 一次获取多个许可,可中断模式,先尝试获取一次,失败加入AQS队列等待 */
public void acquire(int permits) throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
sync.acquireSharedInterruptibly(permits);
}
/** 一次获取多个许可,非中断模式,线尝试获取一次,失败加入AQS队列等待 */
public void acquireUninterruptibly(int permits) {
if (permits < 0) throw new IllegalArgumentException();
//调用的是AQS的方法
sync.acquireShared(permits);
}
/** 一次获取多个许可,成功true,失败false */
public boolean tryAcquire(int permits) {
if (permits < 0) throw new IllegalArgumentException();
return sync.nonfairTryAcquireShared(permits) >= 0;
}
/** 一次获取多个许可,先从尝试获取一次,如果失败则会等待timeout时间,这段时间都没有获取许可,则返回false且加入AQS队列,否则返回ture */
public boolean tryAcquire(int permits, long timeout, TimeUnit unit)
throws InterruptedException {
if (permits < 0) throw new IllegalArgumentException();
return sync.tryAcquireSharedNanos(permits, unit.toNanos(timeout));
}
/** 一次释放多个许可,state值会增加相应的permits,因为没有检查当前state,所以可以当增加可用许可 */
public void release(int permits) {
if (permits < 0) throw new IllegalArgumentException();
//调用AQS方法释放多个许可, 如果释放成功,则唤醒下一个可以节点线程
sync.releaseShared(permits);
}
/** 获取可用的许可次数 */
public int availablePermits() {
return sync.getPermits();
}
/** 摧毁当前的可用许可,对于已经获取的许可没有任何影响,会把当前剩余的许可全部摧毁 */
public int drainPermits() {
return sync.drainPermits();
}
/** 减少许可次数 */
protected void reducePermits(int reduction) {
if (reduction < 0) throw new IllegalArgumentException();
sync.reducePermits(reduction);
}
补充
限流实现代码
public class SemaphoreTest {
public static final Semaphore SEMAPHORE = new Semaphore(100);
public static final AtomicInteger failCount = new AtomicInteger(0);
public static final AtomicInteger successCount = new AtomicInteger(0);
public static void main(String[] args) {
for (int i = 0; i < 1000; i++) {
new Thread(()->seckill()).start();
}
}
public static boolean seckill() {
if (!SEMAPHORE.tryAcquire()) {
System.out.println("no permits, count="+failCount.incrementAndGet());
return false;
}
try {
// 处理业务逻辑
Thread.sleep(2000);
System.out.println("seckill success, count="+successCount.incrementAndGet());
} catch (InterruptedException e) {
// todo 处理异常
e.printStackTrace();
} finally {
SEMAPHORE.release();
}
return true;
}
}
五、总结
无