package com.ora.rmibook.chapter12.pool.simple;
import com.ora.rmibook.chapter12.pool.*;
public class SimplePool implements Pool {
private int _maximumIndex;
private int _currentPosition;
private PoolHelper _helper;
private Object[] _availableObjects;
public SimplePool(int startingSize, int maximumSize, PoolHelper helper) {
_maximumIndex = maximumSize - 1;
_helper = helper;
buildInitialObjects(startingSize, maximumSize);
}
public synchronized Object getObject() {
if (_currentPosition == -1) {
return _helper.create();
}
return getObjectFromArray();
}
private Object getObjectFromArray() {
Object returnValue = _availableObjects[_currentPosition];
_availableObjects[_currentPosition] = null;
_currentPosition--;
return returnValue;
}
public synchronized void returnObject(Object object) {
if (_currentPosition == _maximumIndex) {
_helper.dispose(object);
return;
}
if (!_helper.isObjectStillValid(object)) {
_helper.dispose(object);
return;
}
_currentPosition++;
_availableObjects[_currentPosition] = object;
}
private void buildInitialObjects(int startingSize, int maximumSize) {
_availableObjects = new Object[maximumSize];
int counter;
for (counter = 0; counter < startingSize; counter++) {
_availableObjects[counter] = _helper.create();
}
_currentPosition = startingSize - 1;
}
}
|