//可用对象列表
private final LinkedBlockingDeque idleReferences = new LinkedBlockingDeque();
//所有对象列表
private final ArrayList allReferences = new ArrayList();
borrowObject
//可用对象列表
private final LinkedBlockingDeque idleReferences = new LinkedBlockingDeque();
//所有对象列表
private final ArrayList allReferences = new ArrayList();
public synchronized T borrowObject() throws Exception {
assertOpen();//确定池打开
T obj = null;
boolean newlyCreated = false;
PooledSoftReference ref = null;
while (null == obj) {
if (idleReferences.isEmpty()) {
if (null == factory) {
throw new NoSuchElementException();
} else {
//如果可用列表为空则创建新的对象
newlyCreated = true;
obj = factory.makeObject().getObject();
//累加计数器
createCount++;
// Do not register with the queue
//关联
ref = new PooledSoftReference(new SoftReference(obj));
//添加进所有列表
allReferences.add(ref);
}
} else {
//从可用队列获取对象
ref = idleReferences.pollFirst();
obj = ref.getObject();
// Clear the reference so it will not be queued, but replace with a
// a new, non-registered reference so we can still track this object
// in allReferences
//重建关联
ref.getReference().clear();
ref.setReference(new SoftReference(obj));
}
if (null != factory && null != obj) {
try {
//激活对象
factory.activateObject(ref);
if (!factory.validateObject(ref)) {
throw new Exception("ValidateObject failed");
}
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
try {
destroy(ref);
} catch (Throwable t2) {
PoolUtils.checkRethrow(t2);
// Swallowed
} finally {
obj = null;
}
if (newlyCreated) {
throw new NoSuchElementException(
"Could not create a validated object, cause: " +
t.getMessage());
}
}
}
}
numActive++;
//锁定
ref.allocate();
return obj;
}
returnObject
public synchronized void returnObject(T obj) throws Exception {
boolean success = !isClosed();
//判断对象来自于池【通过对象的equals方法】
final PooledSoftReference ref = findReference(obj);
if (ref == null) {
throw new IllegalStateException(
"Returned object not currently part of this pool");
}
if (factory != null) {
//判断对象合格
if (!factory.validateObject(ref)) {
success = false;
} else {
try {
//钝化对象
factory.passivateObject(ref);
} catch (Exception e) {
success = false;
}
}
}
boolean shouldDestroy = !success;
numActive--;
if (success) {
//如果对象合格并且钝化成功则解除锁定并添加到可用列表中
// Deallocate and add to the idle instance pool
ref.deallocate();
idleReferences.add(ref);
}
notifyAll(); // numActive has changed
if (shouldDestroy && factory != null) {
try {
destroy(ref);
} catch (Exception e) {
// ignored
}
}
}
//默认出队方式
private volatile boolean lifo = BaseObjectPoolConfig.DEFAULT_LIFO;
//后台清理逻辑
class Evictor extends TimerTask
//所有对象列表
private final Map allObjects = new ConcurrentHashMap();
//可用对象列表【双向链表】
private final LinkedBlockingDeque idleObjects = new LinkedBlockingDeque();
borrowObject
public T borrowObject(long borrowMaxWaitMillis) throws Exception {
assertOpen();
//是否在获取对象的时候检查对象,开启的话则检查【主要是检查过期】
AbandonedConfig ac = this.abandonedConfig;
if (ac != null && ac.getRemoveAbandonedOnBorrow() &&
(getNumIdle() < 2) &&
(getNumActive() > getMaxTotal() - 3) ) {
removeAbandoned(ac);
}
PooledObject p = null;
// Get local copy of current config so it is consistent for entire
// method execution
//当池耗尽的时候是否block,如果block的话则会idleObjects.pollFirst(borrowMaxWaitMillis,TimeUnit.MILLISECONDS);否则直接throw new NoSuchElementException("Pool exhausted");
boolean blockWhenExhausted = getBlockWhenExhausted();
boolean create;
long waitTime = 0;
while (p == null) {
create = false;
if (blockWhenExhausted) {
p = idleObjects.pollFirst();
if (p == null) {
create = true;
p = create();
}
if (p == null) {
if (borrowMaxWaitMillis < 0) {
p = idleObjects.takeFirst();
} else {
waitTime = System.currentTimeMillis();
p = idleObjects.pollFirst(borrowMaxWaitMillis,
TimeUnit.MILLISECONDS);
waitTime = System.currentTimeMillis() - waitTime;
}
}
if (p == null) {
throw new NoSuchElementException(
"Timeout waiting for idle object");
}
if (!p.allocate()) {
p = null;
}
} else {
p = idleObjects.pollFirst();
if (p == null) {
create = true;
p = create();
}
if (p == null) {
throw new NoSuchElementException("Pool exhausted");
}
if (!p.allocate()) {
p = null;
}
}
if (p != null) {
try {
//激活对象
factory.activateObject(p);
} catch (Exception e) {
try {
destroy(p);
} catch (Exception e1) {
// Ignore - activation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to activate object");
nsee.initCause(e);
throw nsee;
}
}
//如果获取对象是检查则validateObject
if (p != null && getTestOnBorrow()) {
boolean validate = false;
Throwable validationThrowable = null;
try {
validate = factory.validateObject(p);
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
validationThrowable = t;
}
//检查不通过则destroy
if (!validate) {
try {
destroy(p);
destroyedByBorrowValidationCount.incrementAndGet();
} catch (Exception e) {
// Ignore - validation failure is more important
}
p = null;
if (create) {
NoSuchElementException nsee = new NoSuchElementException(
"Unable to validate object");
nsee.initCause(validationThrowable);
throw nsee;
}
}
}
}
}
updateStatsBorrow(p, waitTime);
return p.getObject();
}
returnObject
public void returnObject(T obj) {
PooledObject p = allObjects.get(obj);
if (!isAbandonedConfig()) {
if (p == null) {
throw new IllegalStateException(
"Returned object not currently part of this pool");
}
} else {
if (p == null) {
return; // Object was abandoned and removed
} else {
// Make sure object is not being reclaimed
synchronized(p) {
final PooledObjectState state = p.getState();
if (state == PooledObjectState.ABANDONED ||
state == PooledObjectState.INVALID) {
return;
} else {
p.markReturning(); // Keep from being marked abandoned
}
}
}
}
long activeTime = p.getActiveTimeMillis();
//验证合格
if (getTestOnReturn()) {
if (!factory.validateObject(p)) {
try {
destroy(p);
} catch (Exception e) {
swallowException(e);
}
updateStatsReturn(activeTime);
return;
}
}
//钝化
try {
factory.passivateObject(p);
} catch (Exception e1) {
swallowException(e1);
try {
destroy(p);
} catch (Exception e) {
swallowException(e);
}
updateStatsReturn(activeTime);
return;
}
if (!p.deallocate()) {
throw new IllegalStateException(
"Object has already been retured to this pool or is invalid");
}
//池大小
int maxIdleSave = getMaxIdle();
if (isClosed() || maxIdleSave > -1 && maxIdleSave