Skip to content

Instantly share code, notes, and snippets.

@ellios
Created July 23, 2012 13:19
Show Gist options
  • Save ellios/3163574 to your computer and use it in GitHub Desktop.
Save ellios/3163574 to your computer and use it in GitHub Desktop.
borrowObject
//将对对象的请求放入请求队列
Latch latch = new Latch();
_allocationQueue.add(latch);
//处理请求队列,三种情况。
//1,池中有可用对象直接赋值给latch,
//2. 没有可用的对象,而且池中的对象数没有达到maxActive,latch的状态为可创建状态
//3. 池子空,且达到最大的maxActive,返回。
allocate();
//处理情况三,大段的代码,有三种处理逻辑,主要介绍下WHEN_EXHAUSTED_BLOCK这种
//先等待一段时间,如果在等待期间连接池仍然处于满负荷状态的话进行处理
latch.wait(waitTime);
//如果超时的话,开始将latch从请求队列清理掉,并抛出异常
if(maxWait > 0 && ((System.currentTimeMillis() - starttime) >= maxWait)) {
synchronized(this) {
// Make sure allocate hasn't already assigned an object
// in a different thread or permitted a new object to be created
if (latch.getPair() == null && !latch.mayCreate()) {
// Remove latch from the allocation queue
_allocationQueue.remove(latch);
} else {
break;
}
}
//抛出等待超时一场
throw new NoSuchElementException("Timeout waiting for idle object");
}
//激活对象,将对象使用状态变为open
_factory.activateObject(latch.getPair().value);
//返回
return latch.getPair().value;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment