FileDocCategorySizeDatePackage
ResourcePool.javaAPI DocExample2436Sun Nov 23 18:03:36 GMT 2003pool

ResourcePool

public class ResourcePool extends Object
A generic resource pool implementation based on factories.

Fields Summary
private ResourceFactory
factory
the factory
private int
maxObjects
counters
private int
curObjects
private boolean
quit
private Set
outResources
resources we have loaned out
private List
inResources
resources we have waiting
Constructors Summary
public ResourcePool(ResourceFactory factory, int maxObjects)
Create a new resource pool that generates objects using the provided factory, and keeps up to maxObjects in the pool.

        this.factory = factory;
        this.maxObjects = maxObjects;
        
        curObjects = 0;
        
        outResources = new HashSet(maxObjects);
        inResources = new LinkedList();
    
Methods Summary
public synchronized voiddestroy()
Destroy the pool

        quit = true;
        notifyAll();
    
public synchronized java.lang.ObjectgetResource()
Retrieve a resource from the pool

        while(!quit) {
        
            // first, try to return a resource from the pool
            if (!inResources.isEmpty()) {
                Object o = inResources.remove(0);
                
                // if the resource is invalid, create a replacement
                if(!factory.validateResource(o))
                    o = factory.createResource();
                
                outResources.add(o);
                return o;
            }
            
            // next, create a new resource if we haven't
            // reached the limit yet
            if(curObjects < maxObjects) {
                Object o = factory.createResource();
                outResources.add(o);
                curObjects++;
                
                return o;
            }
            
            // if no resources are available, wait until one
            // is returned
            try { wait(); } catch(Exception ex) {}
        }
    
        // pool is destroyed
        return null;
    
public synchronized voidreturnResource(java.lang.Object o)
Return a resource to the pool.

        
        // Something is wrong.  Just give up.
        if(!outResources.remove(o))
            return;
        
        inResources.add(o);
        notify();