LimitLatch-学习

简介

LimitLatch,Tomcat控制请求数的并发工具,控制最大的请求数量;

LimitLatch共享锁(但在获取、释放资源时没有用 自旋+CAS);

使用了AQS的通用处理模版,但没有使用state,而是自己使用了limit、count控制;

基本成员

  • Sync

同步对象,继承AQS,实现共享锁的方法 tryAcquireShared、tryReleaseShared

  • count

AtomicLong修饰;用于表示当前获取到资源的数量

  • limit

volatile修饰; 允许获取到资源的最大数

  • released

【待补充】

方法

  • countUpOrAwait
  • countDown
/**
 *  获取资源,成功count+1,否则阻塞
 */
public void countUpOrAwait() throws InterruptedException {
    if (log.isDebugEnabled()) {
        log.debug("Counting up["+Thread.currentThread().getName()+"] latch="+getCount());
    }
    sync.acquireSharedInterruptibly(1);
}
​
​
/**
 * 释放资源,count-1
 */
public long countDown() {
    sync.releaseShared(0);
    long result = getCount();
    if (log.isDebugEnabled()) {
        log.debug("Counting down["+Thread.currentThread().getName()+"] latch="+result);
    }
    return result;
}
复制代码
  • tryAcquireShared
  • tryReleaseShared
​
​
​
/**
 * Sync#tryAcquireShared
 * 获取资源
 */
protected int tryAcquireShared(int ignored) {
    long newCount = count.incrementAndGet();
    // released为true 或 released为false,newCount < limit 认为资源获取成功
    if (!released && newCount > limit) {
        // 新count超过limit后,count-1,将count恢复到原值,不然release-1会有问题
        count.decrementAndGet();
        return -1;
    } else {
        return 1;
    }
}
​
​
/**
 * Sync#tryReleaseShared
 * 释放资源
 */
protected boolean tryReleaseShared(int arg) {
    // count-1 
    count.decrementAndGet();
    return true;
}
​
​
/**
 * 【待补充】
 */
public boolean releaseAll() {
    released = true;
    return sync.releaseShared(0);
}
复制代码

问题

  • 没有用到AQS的state,来表示资源,使用了AtomicCount

【待补充】

  • released字段在tomcat中表示什么

【待补充】

  • #countUpOrAwait、#countdown方法,Tomcat怎么使用的

【待补充】

  • AtomicLong原理是什么,是线程通信的吗?可以不使用volatile修饰

【待补充】

  • 为什么不使用Semaphore来控制能?是因为需要#reset、#release方法吗

【待补充】

猜你喜欢

转载自juejin.im/post/7036607604671545351