1 package com.protomatter.pool; 2 3 52 53 import java.util.*; 54 import com.protomatter.util.*; 55 import com.protomatter.syslog.Syslog; 56 57 66 public abstract class SimpleObjectPool 67 implements ObjectPool 68 { 69 72 protected Object sync = new Object (); 73 74 private List waiters = new ArrayList(); 75 private List checkedOutObjects = new ArrayList(); 76 private boolean monitorCheckedOutObjects = true; 77 78 82 public SimpleObjectPool() 83 { 84 this(true); 85 } 86 87 92 public SimpleObjectPool(boolean monitorCheckedOutObjects) 93 { 94 super(); 95 this.monitorCheckedOutObjects = monitorCheckedOutObjects; 96 } 97 98 105 protected Object getSyncObject() 106 { 107 return this.sync; 108 } 109 110 113 public int getNumWaiters() 114 { 115 return this.waiters.size(); 116 } 117 118 121 public int getObjectsInUse() 122 { 123 return this.checkedOutObjects.size(); 124 } 125 126 132 private final void addToWaiters(Thread t) 133 { 134 synchronized (waiters) 135 { 136 if (!waiters.contains(t)) 137 { 138 waiters.add(t); 139 } 141 } 142 } 143 144 149 public final void removeWaiter(Thread t) 150 { 151 synchronized (waiters) 152 { 153 waiters.remove(t); 154 } 155 } 156 157 160 private final Thread getNextWaiter() 161 { 162 synchronized (waiters) 163 { 164 if (waiters.size() != 0) 165 return (Thread )waiters.remove(0); 166 return null; 167 } 168 } 169 170 178 public ObjectPoolObject checkout() 179 throws Exception 180 { 181 Thread thread = Thread.currentThread(); 182 183 ObjectPoolObject obj = null; 184 while (true) { 186 synchronized (sync) 187 { 188 boolean done = false; 189 190 while (!done) 191 { 192 obj = getNextPoolObject(); 194 if (obj != null) 195 { 196 obj.beforeObjectPoolObjectCheckout(); 197 if (obj.isObjectPoolObjectValid()) 199 { 200 if (monitorCheckedOutObjects) 201 checkedOutObjects.add(obj); 202 return obj; 203 } 204 else 205 { 206 obj.deleteObjectPoolObject(); 207 } 208 } 209 else 210 { 211 done = true; 212 } 213 } 214 } 215 216 synchronized (thread) 221 { 222 addToWaiters(thread); 223 thread.wait(); 224 } 225 } 226 } 227 228 236 public void checkin(ObjectPoolObject opo) 237 throws Exception 238 { 239 opo.afterObjectPoolObjectCheckin(); 240 synchronized(sync) 241 { 242 try 243 { 244 if (opo.isObjectPoolObjectValid()) 245 checkinPoolObject(opo); else 247 opo.deleteObjectPoolObject(); 248 } 249 finally 250 { 251 if (monitorCheckedOutObjects) 254 this.checkedOutObjects.remove(opo); 255 256 Thread waiter = getNextWaiter(); 258 if (waiter != null) 259 { 260 synchronized (waiter) 261 { 262 waiter.notify(); 263 } 264 } 265 } 266 } 267 } 268 269 272 protected List getCheckedOutObjects() 273 { 274 return this.checkedOutObjects; 275 } 276 277 287 protected abstract ObjectPoolObject getNextPoolObject() 288 throws Exception ; 289 290 297 protected abstract void checkinPoolObject(ObjectPoolObject o) 298 throws Exception ; 299 300 307 protected abstract ObjectPoolObject createObjectPoolObject() 308 throws Exception ; 309 } 310 | Popular Tags |