00001
package com.quadcap.sql.lock;
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
import java.util.Iterator;
00042
00043
import com.quadcap.util.Debug;
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054 public class ObjectPool {
00055 PooledObject proto;
00056
00057 public ObjectPool(
PooledObject proto) {
00058
this.proto = proto;
00059 }
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072 PooledObject[]
pool;
00073 int next = 0;
00074
00075 Object
lock =
new Object();
00076
00077 final void resizePool(
int lim) {
00078
PooledObject[] old =
pool;
00079
if (old == null || old.length != lim) {
00080 pool =
new PooledObject[lim];
00081
int f = 0;
00082
if (old != null) {
00083 System.arraycopy(old, 0, pool, 0,
00084 Math.min(old.length, lim));
00085 f = old.length;
00086 }
00087
for (
int i = f; i < lim; i++) {
00088 pool[i] =
proto.
create();
00089 pool[i].
poolIndex = i;
00090 }
00091 }
00092 }
00093
00094 public PooledObject get() {
00095
synchronized (
lock) {
00096
if (
pool == null ||
next >=
pool.length) {
00097 resizePool(
pool == null ?
00098 8 : (
pool.length + (
pool.length >> 2)));
00099 }
00100
PooledObject obj =
pool[
next++];
00101
if (obj.
live)
throw new RuntimeException(
"Already live: " + obj);
00102 obj.
live =
true;
00103
return obj;
00104 }
00105 }
00106
00107 public void release(
PooledObject obj) {
00108
synchronized (
lock) {
00109
if (!obj.
live)
throw new RuntimeException(
"Not live: " + obj);
00110 obj.
live =
false;
00111
final int idx = obj.
poolIndex;
00112
if (
pool[idx] != obj)
00113
throw new RuntimeException(
"Pool check: " + obj);
00114
final int last = --
next;
00115
if (idx != last) {
00116
pool[idx] =
pool[last];
00117 pool[idx].
poolIndex = idx;
00118 pool[last] = obj;
00119 obj.
poolIndex = last;
00120 }
00121 }
00122 }
00123
00124
00125
00126
00127
00128 public Iterator
iterator() {
00129
return new Iterator() {
00130
int idx = 0;
00131
00132
public boolean hasNext() {
00133
return idx <
next;
00134 }
00135
00136
public Object
next() {
00137
return idx < next ?
pool[idx++] : null;
00138 }
00139
public void remove() {}
00140 };
00141 }
00142
00143
00144 public String
toString() {
00145 String s = getClass().getName();
00146
int idx = s.lastIndexOf(
'.');
00147
if (idx >= 0) s = s.substring(idx+1);
00148 StringBuffer sb =
new StringBuffer(s);
00149 sb.append(
"(");
00150
int len = s.length() + 1;
00151
for (
int i = 0; i <
next; i++) {
00152
if (i > 0) sb.append(
',');
00153 String p =
pool[i].
toString();
00154
final int plen = p.length();
00155 len += plen + 1;
00156
if (len > 80) {
00157 sb.append(
'\n');
00158 len = plen;
00159 }
00160 sb.append(p);
00161 }
00162 sb.append(
')');
00163
return sb.toString();
00164 }
00165
00166
00167 }