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只是使用中的一个典型场景.