分析工具类Semaphore的实现
1,Semaphore 是什么?
Semaphore 字面意思是信号量的意思,它的作用是控制访问特定资源的线程数目。Semaphore的构造函数中,默认会把Sync对象创建为NonfairSync对象,这被称为“非公平锁”;而另一个构造函数Semaphore(int permits, boolean fair)传入参数为true时将会把Sync对象创建为“公平锁”(FairSync);
首先看非公平模式
主要看两个方法:acquire(int permits)、release(int permits)
2. acquire()方法实现:
1)方法中只有一行代码,调用了AQS中的acquireSharedInterruptibly方法,该方法在尝试获取锁时可被中断。2)如果tryAcquireShared(arg) < 0 ,则进入acquireSharedInterruptibly方法中。
首先看tryAcquireShared(arg)方法:
该方法调用了nonfairTryAcquireShared方法如下:
final int nonfairTryAcquireShared(int acquires) { for (;;) {
int available = getState();
int remaining = available - acquires;
if (remaining < 0 ||
compareAndSetState(available, remaining))
return remaining;
}
}
从上面方法中可以理解:若获取锁状态的线程数acquires不够获取的情况返回值会小于0;当compareAndSetState(available, remaining)更新成功的情况返回值大于0;
1)当返回值remaining大于0时,则表示acquires个线程已同时成功获取当前资源。2)当返回值remaining小于0时,进入doAcquireSharedInterruptibly方法,
public final void acquireSharedInterruptibly(int arg) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
该方法会将当前线程打包成Node节点(并设置成为共享模式)然后加入到队尾。然后在自旋方法中,获取Node节点的前驱节点,若前驱节点为head节点,则重新尝试获取锁状态并取得返回值r,此时,
若r>=0则通过传播的方式依次唤醒所有可被唤醒的后继节点。若r<0则判断是否需要阻塞等待,若需要则进入阻塞状态。
3. release方法实现:
1)该方法会调用AQS中的releaseShared方法,方法如下:
public final boolean releaseShared(int arg) { if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
其中tryReleaseShared是抽象模板方法,需要Semaphore自实现,若tryReleaseShared返回true则进入doReleaseShared()方法,并返回true,否则返回false;
先看tryReleaseShared方法实现:
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;
}
}
该方法可理解为:当releases个线程释放资源时,会同时释放releases个锁状态,并返回true表示资源锁释放成功。注:releases可以理解为线程个数。
此时,若返回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;
}
}
该方法从头节点开始依次唤醒所有可被唤醒的后继节点。
初步对Semaphore源码进行解析,后面会进行改进自己对源码的理解。。。
以上是 分析工具类Semaphore的实现 的全部内容, 来源链接: utcz.com/z/518643.html