背景
在之前的文章中介绍了ReentrantLock、Condition和CountDownLatch这些在JAVA多线程中常用的类,它们各有各的使用场景。ReentrantLock通常用于需要可重入锁定、带超时时间的获取锁等场景,Condition通常用于将线程加入条件等待队列/唤醒的场景,CountDownLatch通常用于在程序执行过程中设置等待点,待一定数额的线程全部到达等待点之后集合在一起再继续执行的场景。其实在实际工程应用中,还有一种场景比较常见。比如给定一个资源数目有限的资源池,假设资源数目为N,每一个线程均可获取一个资源,但是当资源分配完毕时,后来线程需要阻塞等待,直到前面已持有资源的线程释放资源之后才能继续。这种场景就非常适合用Semaphore来实现。
Semaphore的主要方法
Semaphore的主要方法主要有获取资源(acquire)方法和释放资源(release)方法。我们会在下文中一一加以介绍。
获取资源方法
构造函数中设置了Semaphore的资源数量。acquire方法首先获取当前的资源数量,然后减去acquire方法要获取的数量,如果资源已耗尽,即当前资源数-要获取的资源数<0,则进入到doAcquireShared方法中,将当前线程包装成节点,插入到线程同步队列的尾部,然后将当前线程park。反之,则成功获取到资源,采用CAS操作将当前资源数做更新。
public void acquire() throws InterruptedException {
sync.acquireSharedInterruptibly(1);
}
public final void acquireSharedInterruptibly(int arg)
throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
if (tryAcquireShared(arg) < 0)
doAcquireSharedInterruptibly(arg);
}
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);
}
}
与ReentrantLock类似的,Semaphore获取资源的时候也存在公平方式(FairSync)和非公平方式(NonFairSync)。FairSync会检查当前线程同步队列中是否已有排队等待的其他线程,如果有的话,则不能抢在他们之前获取资源,需要排队等待;NonFairSync则可以直接插队。
释放资源方法
release方法会在调用时,获取当前资源数,然后通过CAS操作的方式,将资源数设置为当前资源数+释放资源数,然后从线程同步队列的头部开始,获取其头节点的后继节点,将其唤醒。
public void release() {
sync.releaseShared(1);
}
public final boolean releaseShared(int arg) {
if (tryReleaseShared(arg)) {
doReleaseShared();
return true;
}
return false;
}
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;
}
}