简单的池实现(二)
并且资源数小于最大资源数,则调用{@link #add()} 生成资源,并设置状态返回此资源
* @return
*/
private synchronized T nativeBorrow()
{
for (PoolDataUnit unit : al) {
if(System.currentTimeMillis()-unit.getBorrowTime() > maxPeriod)//如果发现资源已过期,直接调remove方法进行移除资源
remove(unit.getT());
if(!unit.isBorrowed())//如果此资源未使用或者此资源被使用的时间超过了时限
{
unit.setBorrowed(true);
unit.setBorrowTime(System.currentTimeMillis());
return unit.getT();
}
}
if(al.size() < maxSize)
{
T t = add();
PoolDataUnit unit = new PoolDataUnit(t);
al.add(unit);
unit.setBorrowed(true);
unit.setBorrowTime(System.currentTimeMillis());
return t;
}
return null;
}
/**
* 还回对象,把对象放回池中,并通知所有等待获取资源的线程
* @param t
*/
public synchronized void lent(T t)
{
for (PoolDataUnit unit : al) {
if(unit.getT().equals(t))
{
unit.setBorrowed(false);
unit.setBorrowTime(System.currentTimeMillis());
notifyAll();
return;
}
}
remove(t);
}
}