PoolableObjectFactory的几个方法总结
An interface defining life-cycle methods for instances to be served by an ObjectPool
.
By contract, when an ObjectPool
delegates to a PoolableObjectFactory
,
-
makeObject
is called whenever a new instance is needed. -
activateObject
is invoked on every instance that has beenpassivated
before it isborrowed
from the pool. -
validateObject
is invoked onactivated
instances to make sure they can beborrowed
from the pool.validateObject
may also be used to test an instance beingreturned
to the pool before it ispassivated
. It will only be invoked on an activated instance. -
passivateObject
is invoked on every instance when it is returned to the pool. -
destroyObject
is invoked on every instance when it is being "dropped" from the pool (whether due to the response fromvalidateObject
, or for reasons specific to the pool implementation.) There is no guarantee that the instance being destroyed will be considered active, passive or in a generally consistent state.
参考:http://commons.apache.org/proper/commons-pool/api-1.6/org/apache/commons/pool/PoolableObjectFactory.html
对于使用pool来说基本流程:
Object obj = null;
try {
obj = pool.borrowObject();
try {
//...use the object...
} catch(Exception e) {
// invalidate the object
pool.invalidateObject(obj);
// do not return the object to the pool twice
obj = null;
} finally {
// make sure the object is returned to the pool
if(null != obj) {
pool.returnObject(obj);
}
}
} catch(Exception e) {
// failed to borrow an object
}
调用 pool的borrowObject()会触发内部调用poolableObjectFactory,基本流程如下:
1. 调用makeObject
()获取对象,一般需要实现。
2. 调用activateObject(),默认是一个空实现。
调用 pool的returnObject()会触发内部调用poolableObjectFactory,基本流程如下:
1. 调用validateObject()确保对象有效,默认实现返回True。
2. 调用passivateObject()让对象钝化,默认是一个空实现,貌似也没啥用。
2. 如果validateObject()返回False,调用destroyObject()。