1、方法
public void acquire()
public void acquireUninterruptibly()
public void release()
public boolean tryAcquire(int permits)
2、原理
Semaphore原理比较简单,类似ReentrantLock,使用AQS的模板模式来进行实现。
//Semaphore.java
abstract static class Sync extends AbstractQueuedSynchronizer。。。
Sync有两种子类,一个公平,一个非公平。
Semaphore构建通常使用如下构造方法,默认是使用非公平模式。
public Semaphore(int permits) {
sync = new NonfairSync(permits);
}
public Semaphore(int permits, boolean fair) {
sync = fair ? new FairSync(permits) : new NonfairSync(permits);
}
2-1、acquire
还是借助AQS的双向等待队列来实现。
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
//拿state,失败进入核心等待方法
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
下面来看核心的等待方法。
private void doAcquireSharedInterruptibly(int arg)
throws InterruptedException {
//入队列
final Node node = addWaiter(Node.SHARED);
boolean failed = true;
try {
//CAS自旋volatile变量
for (;;) {
final Node p = node.predecessor();//前一个节点
//如果是老二,可以做动作,否则进行park
if (p == head) {
//尝试取state,且state-arg。
int r = tryAcquireShared(arg);
if (r >= 0) {
setHeadAndPropagate(node, r);
p.next = null; // help GC
failed = false;
return;
}
}
//在ReentratLock研究过这一段,就是遍历队列,然后park
if (shouldParkAfterFailedAcquire(p, node) &&
parkAndCheckInterrupt())
throw new InterruptedException();
}
} finally {
if (failed)
cancelAcquire(node);
}
}
2-2、release
release更简单,就是释放state,然后队列下一节点进行unpark即可,由于肯定当前线程执行,都不需要考虑并发。
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
先来看tryReleaseShared,就是state+arg
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;
}
}
再来看doReleaseShared,核心就是唤醒下一个节点。
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;
}
}
通过ReentrantLock看懂了AQS后,深深感觉Semaphore没啥东西。。。