Semaphore用作流控信号量在rocketmq中有很好的例子
Semaphore可以用来控制同一时刻访问共享资源的线程数量
SemaphoreReleaseOnlyOnce#release
通过cas保证只释放一次
public void release() {
if (this.semaphore != null) {
if (this.released.compareAndSet(false, true)) {
this.semaphore.release();
}
}
}
使用tryAcquire获得许可,tryAcquire可以加超时时间
boolean acquired = this.semaphoreAsync.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS);
if (acquired) {
final SemaphoreReleaseOnlyOnce once = new SemaphoreReleaseOnlyOnce(this.semaphoreAsync);
long costTime = System.currentTimeMillis() - beginStartTime;
if (timeoutMillis < costTime) {
once.release();
throw new RemotingTimeoutException("invokeAsyncImpl call timeout");
}