1 46 package org.mr.core.util; 47 48 import org.apache.commons.logging.Log; 49 import org.apache.commons.logging.LogFactory; 50 51 52 65 public abstract class ObjectPool { 66 67 private Object [] acquiredObjects = null; 68 private Object acquiredObjectsLock = new Object (); 69 70 private Object [] releasedObjects = null; 71 private Object releasedObjectsLock = new Object (); 72 73 private int maxNumOfObjects = 0; 74 private int objectsInAcquiredPool = 0; 75 private int objectsInReleasedPool = 0; 76 private Log log; 77 78 79 80 private String poolName = null; 81 82 83 private int highWaterMark = 0; 84 85 86 87 89 90 94 public ObjectPool(int numOfObjects, String poolName) { 95 this.poolName = poolName; 96 this.maxNumOfObjects = numOfObjects; 97 log=LogFactory.getLog("ObjectPool"); 98 99 acquiredObjects = new Object [maxNumOfObjects]; 100 releasedObjects = new Object [maxNumOfObjects]; 101 102 for(int i=0; i < maxNumOfObjects; i++) 103 acquiredObjects[i] = newInstance(); 104 105 objectsInAcquiredPool = acquiredObjects.length; 106 } 108 109 110 113 public final int getMaxNumOfObjects() { 114 return maxNumOfObjects; 115 } 117 120 public final int getRemainingObjectsInPool() { 121 return objectsInAcquiredPool; 122 } 124 125 129 public final String getPoolName(){ 130 return poolName; 131 } 133 134 137 public final int getHighWaterMark() { 138 return highWaterMark; 139 } 141 142 143 144 149 public final Object acquireObject() { 150 synchronized (acquiredObjectsLock){ 151 Object obj = null; 152 if(objectsInAcquiredPool == 0){ 153 flip(); 154 } if(objectsInAcquiredPool == 0){ 156 try{ 157 obj = newInstance(); 158 } catch(Exception ex){ 160 if(log.isFatalEnabled()){ 161 log.fatal("Exception in init method of Object Pool - 'newInstance()'. ",ex); 162 } } } else{ 166 objectsInAcquiredPool--; 167 obj = acquiredObjects[objectsInAcquiredPool]; 168 acquiredObjects[objectsInAcquiredPool] = null; 169 170 int nAcquiredObjects = acquiredObjects.length - objectsInAcquiredPool; 172 if (nAcquiredObjects > highWaterMark) 173 highWaterMark = nAcquiredObjects; 174 } return obj; 176 } } 179 180 185 public final void releaseObject(Object theObj) { 186 synchronized(releasedObjectsLock){ 187 188 if (objectsInReleasedPool>= maxNumOfObjects) 189 return; 190 191 releasedObjects[objectsInReleasedPool++] = theObj; 192 } } 195 private final void flip(){ 196 synchronized(releasedObjectsLock){ 197 int tmp = objectsInAcquiredPool; 198 Object [] tmpArray = acquiredObjects; 199 200 acquiredObjects = releasedObjects; 201 releasedObjects = tmpArray; 202 203 objectsInAcquiredPool = objectsInReleasedPool; 204 objectsInReleasedPool = tmp; 205 } } 208 209 210 public final void reset() { 211 if(log.isDebugEnabled()){ 212 log.debug("Resetting pool stats of " + poolName); 213 } 215 highWaterMark = 0; 216 } 218 219 225 public abstract Object newInstance(); 226 227 230 public abstract String getObjectInPoolClassName(); 231 232 } 233 | Popular Tags |