// Copyright 2000 Jonathan White // Use/modify this however you want, just keep this and the previous line package mt.util; import java.util.*; /* Version 1.0 - First version. This class pools objects, ensureing that there are never more than object_max instances. It is up to the client to check the object back in. If they are not then deadlock will occur. Object should be loaded via the PooledObjectFactory, not the addObject() method. */ /* There is no functionality at this point that ensures an objects validity, eg a database connection has not timed out. */ public class ObjectPool extends Object{ protected Deque pool = new Deque(); protected Object wait_put = new Object(); protected Object wait_get = new Object(); protected int object_max = 10; protected int object_use = 0; //number of object currently stored protected int object_pol = 0; //total number of object in and out protected PooledObjectFactory factory = null; public ObjectPool(PooledObjectFactory pof, int max){ factory = pof; object_max = max; } public int size(){return object_pol;} public int getIntSize(){return object_use;} public int getMaxSize(){return object_max;} public synchronized void setMaxSize(int size){object_max = size;} public synchronized void addObject(Object o){ object_pol++; object_use++; pool.enqueue(o); } public Object getObject() throws Exception { Object o = null; //Lock get synchronized(wait_get){ //Lock put synchronized(wait_put){ //its empty-- we need to wait or if possible // create another one. if(pool.isEmpty()){ //are we at the limit yet if(object_pol < object_max) //no...create another object addObject(factory.getNewPoolObject()); else{ //yes... try{ //...Wait for an item to be //put on the queue; wait_put.wait(); }catch(Exception e){ e.printStackTrace(); } } } //now lets grab it! o = pool.dequeue(); //we are using it! object_use--; } } return o; } public void putObject(Object o){ //Make sure we get exclusive lock synchronized(wait_put){ //Add to queue pool.enqueue(o); object_use++; //Notify that we are done and get will quit waiting // when we release this lock. wait_put.notify(); } } }