1 package com.quadcap.sql.lock; 2 3 40 41 import java.util.Iterator ; 42 43 import com.quadcap.util.Debug; 44 45 49 54 public class ObjectPool { 55 PooledObject proto; 56 57 public ObjectPool(PooledObject proto) { 58 this.proto = proto; 59 } 60 61 PooledObject[] pool; 73 int next = 0; 74 75 Object lock = new Object (); 76 77 final void resizePool(int lim) { 78 PooledObject[] old = pool; 79 if (old == null || old.length != lim) { 80 pool = new PooledObject[lim]; 81 int f = 0; 82 if (old != null) { 83 System.arraycopy(old, 0, pool, 0, 84 Math.min(old.length, lim)); 85 f = old.length; 86 } 87 for (int i = f; i < lim; i++) { 88 pool[i] = proto.create(); 89 pool[i].poolIndex = i; 90 } 91 } 92 } 93 94 public PooledObject get() { 95 synchronized (lock) { 96 if (pool == null || next >= pool.length) { 97 resizePool(pool == null ? 98 8 : (pool.length + (pool.length >> 2))); 99 } 100 PooledObject obj = pool[next++]; 101 if (obj.live) throw new RuntimeException ("Already live: " + obj); 102 obj.live = true; 103 return obj; 104 } 105 } 106 107 public void release(PooledObject obj) { 108 synchronized (lock) { 109 if (!obj.live) throw new RuntimeException ("Not live: " + obj); 110 obj.live = false; 111 final int idx = obj.poolIndex; 112 if (pool[idx] != obj) 113 throw new RuntimeException ("Pool check: " + obj); 114 final int last = --next; 115 if (idx != last) { 116 pool[idx] = pool[last]; 117 pool[idx].poolIndex = idx; 118 pool[last] = obj; 119 obj.poolIndex = last; 120 } 121 } 122 } 123 124 128 public Iterator iterator() { 129 return new Iterator () { 130 int idx = 0; 131 132 public boolean hasNext() { 133 return idx < next; 134 } 135 136 public Object next() { 137 return idx < next ? pool[idx++] : null; 138 } 139 public void remove() {} 140 }; 141 } 142 143 public String toString() { 145 String s = getClass().getName(); 146 int idx = s.lastIndexOf('.'); 147 if (idx >= 0) s = s.substring(idx+1); 148 StringBuffer sb = new StringBuffer (s); 149 sb.append("("); 150 int len = s.length() + 1; for (int i = 0; i < next; i++) { 152 if (i > 0) sb.append(','); 153 String p = pool[i].toString(); 154 final int plen = p.length(); 155 len += plen + 1; 156 if (len > 80) { 157 sb.append('\n'); 158 len = plen; 159 } 160 sb.append(p); 161 } 162 sb.append(')'); 163 return sb.toString(); 164 } 165 } 168 | Popular Tags |