package org.apache.commons.pool;
public interface PoolableObjectFactory<T> {
T makeObject() throwsException;
void destroyObject(T obj)throws Exception;
boolean validateObject(T obj);
void activateObject(T obj)throws Exception;
void passivateObject(T obj)throws Exception;
}
//部分代码
package org.apache.commons.pool.impl;
public class StackObjectPool<T>extendsBaseObjectPool<T> implements ObjectPool<T>{
@Deprecated
protected Stack<T>_pool =null;
@Deprecated
protected PoolableObjectFactory<T>_factory =null;
//传值时_factory实现PoolableObjectFactory接口,要覆写其五个方法
@Override
public synchronized T borrowObject()throwsException {
assertOpen();
T obj = null;
boolean newlyCreated =false;
while (null == obj) {
if (!_pool.empty()) {
obj = _pool.pop();//池中有对象则直接取
} else {
if(null ==_factory) {
throw new NoSuchElementException();
} else {
obj = _factory.makeObject();
//池中有无对象,则创建对象
newlyCreated =true;
if (obj ==null) {
throw new NoSuchElementException("PoolableObjectFactory.makeObject()returned null.");
}
}
}
if (null !=_factory &&null != obj) {
try {
_factory.activateObject(obj);
if (!_factory.validateObject(obj)) {
throw new Exception("ValidateObject failed");
}
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
try {
_factory.destroyObject(obj);
} 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++;
return obj;
}
@Override
public synchronized void returnObject(T obj) throws Exception {
boolean success = !isClosed();
if(null !=_factory) {
if(!_factory.validateObject(obj)) {
success = false;
} else {
try {
_factory.passivateObject(obj);
} catch(Exception e) {
success = false;
}
}
}
boolean shouldDestroy = !success;
_numActive--;
if (success) {
T toBeDestroyed = null;
if(_pool.size() >=_maxSleeping){
shouldDestroy = true;
toBeDestroyed = _pool.remove(0);// remove the stalest object
}
_pool.push(obj);//将对象添加到池中
obj = toBeDestroyed;// swap returned obj with the stalest one so it can bedestroyed
}
notifyAll(); // _numActive has changed
if(shouldDestroy) {// by constructor, shouldDestroy is false when _factory is null
try {
_factory.destroyObject(obj);
} catch(Exception e) {
// ignored
}
}
}
@Override
public synchronized void clear() {
if(null !=_factory) {
Iterator<T> it =_pool.iterator();
while(it.hasNext()) {
try {
_factory.destroyObject(it.next());
} catch(Exception e) {
// ignore error, keep destroying the rest
}
}
}
_pool.clear(); // Vector-->clear()-->removeAllElements();
}
@Override
public void close() throws Exception { //释放池对象
super.close(); // BasicObjectPool---> closed =true;
clear();
}
java.util.Vector--->
public synchronized void removeAllElements(){
modCount++;
// Let gc do its work
for (int i = 0; i <elementCount; i++)
elementData[i] = null;
elementCount = 0;
}
例子可以参考 博文 http://blog.csdn.net/kongxx/article/details/6607083