FileDocCategorySizeDatePackage
ThreadedPool1.javaAPI DocExample2590Thu Nov 08 00:22:38 GMT 2001com.ora.rmibook.chapter12.pool.thread1

ThreadedPool1

public class ThreadedPool1 extends Object implements Pool

Fields Summary
private int
_maximumSize
private Vector
_availableObjects
private int
_totalNumberOfObjects
private PoolHelper
_helper
private ObjectCreator
_creator
Constructors Summary
public ThreadedPool1(String poolName, int maximumSize, PoolHelper helper)

        _maximumSize = maximumSize;
        _helper = helper;
        _availableObjects = new Vector();
        startCreatorThread(poolName);
    
Methods Summary
protected voidcreateAndAddObject()

        Object createdObject = null;

        if (_totalNumberOfObjects < _maximumSize) {
            Object newObject = _helper.create();

            _availableObjects.add(newObject);
            _totalNumberOfObjects++;
        }
        if (null != createdObject) {
            notifyWaitingGets();
        }
        return;
    
private java.lang.ObjectgetLocallyAvailableObject()

        // Locks the container while we check for values.
        // That way, we don't simultaneously vend the same object
        // to two different requests
        synchronized (_availableObjects) {
            if (!_availableObjects.isEmpty()) {
                int lastPosition = _availableObjects.size() - 1;

                return _availableObjects.remove(lastPosition);
            }
        }
        return null;
    
public java.lang.ObjectgetObject()

        Object returnValue = null;

        while (null == (returnValue = getLocallyAvailableObject())) {
            _creator.askForObject();
            waitForAvailableObject();
        }
        return returnValue;
    
private synchronized voidnotifyWaitingGets()

        notify();
    
public voidreturnObject(java.lang.Object object)

        if (_helper.isObjectStillValid(object)) {
            _availableObjects.add(object);
            notifyWaitingGets();
        } else {
            _helper.dispose(object);
            _totalNumberOfObjects--;
        }
        return;
    
private voidstartCreatorThread(java.lang.String poolName)

        _creator = new ObjectCreator(this);
        Thread creatorThread = new Thread(_creator, poolName + " creation thread");

        creatorThread.setPriority(Thread.NORM_PRIORITY - 2);
        creatorThread.start();
    
private synchronized voidwaitForAvailableObject()

        try {
            wait();
        } catch (InterruptedException e) {/*ignored*/
        }