Tomcat线程工具类中有个LimitLatch,这是一个锁存器类.它的作用就是在多线程的情况下控制并发.使用了java的多线程框架中的同步器AbstractQueuedSynchronizer.锁存器类主要用在接受连接的场景,从它的名字来看这是一个有限限制的锁存器.也就是可以控制最大的并非数.当超过这个并发数的时候就把当前请求并发执行的线程放入到等待队列中.待有释放线程时才按FIFO的方式执行等待队列中的线程.
LimitLatch的存在就能使请求到达Endpoint的时候可以在到达最大并发的时候进行等待,待有处理完的链接释放资源立刻按先进先出的规则进行链接的处理.它起到了控制并发和缓冲的作用.具体可以看下代码
public class LimitLatch { private class Sync extends AbstractQueuedSynchronizer { private static final long serialVersionUID = 1L; public Sync() { } @Override protected int tryAcquireShared(int ignored) { long newCount = count.incrementAndGet(); if (!released && newCount > limit) { // Limit exceeded count.decrementAndGet(); return -1; } else { return 1; } } @Override protected boolean tryReleaseShared(int arg) { count.decrementAndGet(); return true; } } private final Sync sync; private final AtomicLong count; private volatile long limit; private volatile boolean released = false; /** * Instantiates a LimitLatch object with an initial limit. * @param limit - maximum number of concurrent acquisitions of this latch */ public LimitLatch(long limit) { this.limit = limit; this.count = new AtomicLong(0); this.sync = new Sync(); } /** * Acquires a shared latch if one is available or waits for one if no shared * latch is current available. */ public void countUpOrAwait() throws InterruptedException { sync.acquireSharedInterruptibly(1); } /** * Releases a shared latch, making it available for another thread to use. * @return the previous counter value */ public long countDown() { sync.releaseShared(0); long result = getCount(); return result; } /** * Releases all waiting threads and causes the {@link #limit} to be ignored * until {@link #reset()} is called. */ public boolean releaseAll() { released = true; return sync.releaseShared(0); } /** * Resets the latch and initializes the shared acquisition counter to zero. * @see #releaseAll() */ public void reset() { this.count.set(0); released = false; } /** * Returns <code>true</code> if there is at least one thread waiting to * acquire the shared lock, otherwise returns <code>false</code>. */ public boolean hasQueuedThreads() { return sync.hasQueuedThreads(); } /** * Provide access to the list of threads waiting to acquire this limited * shared latch. */ public Collection<thread> getQueuedThreads() { return sync.getQueuedThreads(); } }
上面是该类的主要代码countUpOrAwait是获取锁,没有得到的话线程就进行等待.countDown是释放锁.这两个是最常使用的.从代码中我们也可以很清楚的看到这些功能均是依赖于它的一个内部类Sync,这个类继承了AbstractQueuedSynchronizer.这是一个典型的同步器的实现.其中等待线程的队列和挂起的规则都是在AbstractQueuedSynchronizer虚类里面实现的.AbstractQueuedSynchronizer为实现依赖于先进先出 (FIFO) 等待队列的阻塞锁定和相关同步器(信号量,事件等等)提供一个框架.在AbstractQueuedSynchronizer的实现中有个内部类Node,它是挂起线程所存在的节点,其中挂起线程的内部结构就是这个Node组成的链表.有兴趣的话可以看下该类的源码,同时AbstractQueuedSynchronizer的API描述中也有这个类很详细的用法.Tomcat的LimitLatch只是使用中的一个典型场景.