/
SoftReferenceObjectPool.java
364 lines (338 loc) · 13.7 KB
/
SoftReferenceObjectPool.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.datanucleus.store.rdbms.datasource.dbcp.pool.impl;
import java.lang.ref.SoftReference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.Reference;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
import org.datanucleus.store.rdbms.datasource.dbcp.pool.BaseObjectPool;
import org.datanucleus.store.rdbms.datasource.dbcp.pool.ObjectPool;
import org.datanucleus.store.rdbms.datasource.dbcp.pool.PoolableObjectFactory;
import org.datanucleus.store.rdbms.datasource.dbcp.pool.PoolUtils;
/**
* A {@link java.lang.ref.SoftReference SoftReference} based
* {@link ObjectPool}.
*
* @author Rodney Waldhoff
* @author Sandy McArthur
* @version $Revision: 965338 $ $Date: 2010-07-18 21:09:29 -0400 (Sun, 18 Jul 2010) $
* @since Pool 1.0
*/
public class SoftReferenceObjectPool extends BaseObjectPool implements ObjectPool {
/**
* Create a <code>SoftReferenceObjectPool</code> without a factory.
* {@link #setFactory(PoolableObjectFactory) setFactory} should be called
* before any attempts to use the pool are made.
* Generally speaking you should prefer the {@link #SoftReferenceObjectPool(PoolableObjectFactory)} constructor.
*
* @see #SoftReferenceObjectPool(PoolableObjectFactory)
* @deprecated to be removed in pool 2.0. Use {@link #SoftReferenceObjectPool(PoolableObjectFactory)}.
*/
public SoftReferenceObjectPool() {
_pool = new ArrayList();
_factory = null;
}
/**
* Create a <code>SoftReferenceObjectPool</code> with the specified factory.
*
* @param factory object factory to use.
*/
public SoftReferenceObjectPool(PoolableObjectFactory factory) {
_pool = new ArrayList();
_factory = factory;
}
/**
* Create a <code>SoftReferenceObjectPool</code> with the specified factory and initial idle object count.
*
* @param factory object factory to use.
* @param initSize initial size to attempt to prefill the pool.
* @throws Exception when there is a problem prefilling the pool.
* @throws IllegalArgumentException when <code>factory</code> is <code>null</code>.
* @deprecated because this is a SoftReference pool, prefilled idle obejects may be garbage collected before they are used.
* To be removed in Pool 2.0.
*/
public SoftReferenceObjectPool(PoolableObjectFactory factory, int initSize) throws Exception, IllegalArgumentException {
if (factory == null) {
throw new IllegalArgumentException("factory required to prefill the pool.");
}
_pool = new ArrayList(initSize);
_factory = factory;
PoolUtils.prefill(this, initSize);
}
/**
* <p>Borrow an object from the pool. If there are no idle instances available in the pool, the configured
* factory's {@link PoolableObjectFactory#makeObject()} method is invoked to create a new instance.</p>
*
* <p>All instances are {@link PoolableObjectFactory#activateObject(Object) activated} and
* {@link PoolableObjectFactory#validateObject(Object) validated} before being returned by this
* method. If validation fails or an exception occurs activating or validating an idle instance,
* the failing instance is {@link PoolableObjectFactory#destroyObject(Object) destroyed} and another
* instance is retrieved from the pool, validated and activated. This process continues until either the
* pool is empty or an instance passes validation. If the pool is empty on activation or
* it does not contain any valid instances, the factory's <code>makeObject</code> method is used
* to create a new instance. If the created instance either raises an exception on activation or
* fails validation, <code>NoSuchElementException</code> is thrown. Exceptions thrown by <code>MakeObject</code>
* are propagated to the caller; but other than <code>ThreadDeath</code> or <code>VirtualMachineError</code>,
* exceptions generated by activation, validation or destroy methods are swallowed silently.</p>
*
* @throws NoSuchElementException if a valid object cannot be provided
* @throws IllegalStateException if invoked on a {@link #close() closed} pool
* @throws Exception if an exception occurs creating a new instance
* @return a valid, activated object instance
*/
public synchronized Object borrowObject() throws Exception {
assertOpen();
Object obj = null;
boolean newlyCreated = false;
while(null == obj) {
if(_pool.isEmpty()) {
if(null == _factory) {
throw new NoSuchElementException();
} else {
newlyCreated = true;
obj = _factory.makeObject();
}
} else {
SoftReference ref = (SoftReference)(_pool.remove(_pool.size() - 1));
obj = ref.get();
ref.clear(); // prevent this ref from being enqueued with refQueue.
}
if (null != _factory && null != obj) {
try {
_factory.activateObject(obj);
if (!_factory.validateObject(obj)) {
throw new Exception("ValidateObject failed");
}
} catch (Throwable t) {
PoolUtils.checkRethrow(t);
try {
_factory.destroyObject(obj);
} catch (Throwable t2) {
PoolUtils.checkRethrow(t2);
// Swallowed
} finally {
obj = null;
}
if (newlyCreated) {
throw new NoSuchElementException(
"Could not create a validated object, cause: " +
t.getMessage());
}
}
}
}
_numActive++;
return obj;
}
/**
* <p>Returns an instance to the pool after successful validation and passivation. The returning instance
* is destroyed if any of the following are true:<ul>
* <li>the pool is closed</li>
* <li>{@link PoolableObjectFactory#validateObject(Object) validation} fails</li>
* <li>{@link PoolableObjectFactory#passivateObject(Object) passivation} throws an exception</li>
* </ul>
*
* <p>Exceptions passivating or destroying instances are silently swallowed. Exceptions validating
* instances are propagated to the client.
*
* @param obj instance to return to the pool
*/
public synchronized void returnObject(Object obj) throws Exception {
boolean success = !isClosed();
if (_factory != null) {
if(!_factory.validateObject(obj)) {
success = false;
} else {
try {
_factory.passivateObject(obj);
} catch(Exception e) {
success = false;
}
}
}
boolean shouldDestroy = !success;
_numActive--;
if(success) {
_pool.add(new SoftReference(obj, refQueue));
}
notifyAll(); // _numActive has changed
if (shouldDestroy && _factory != null) {
try {
_factory.destroyObject(obj);
} catch(Exception e) {
// ignored
}
}
}
/**
* {@inheritDoc}
*/
public synchronized void invalidateObject(Object obj) throws Exception {
_numActive--;
if (_factory != null) {
_factory.destroyObject(obj);
}
notifyAll(); // _numActive has changed
}
/**
* <p>Create an object, and place it into the pool.
* addObject() is useful for "pre-loading" a pool with idle objects.</p>
*
* <p>Before being added to the pool, the newly created instance is
* {@link PoolableObjectFactory#validateObject(Object) validated} and
* {@link PoolableObjectFactory#passivateObject(Object) passivated}. If validation
* fails, the new instance is {@link PoolableObjectFactory#destroyObject(Object) destroyed}.
* Exceptions generated by the factory <code>makeObject</code> or <code>passivate</code> are
* propagated to the caller. Exceptions destroying instances are silently swallowed.</p>
*
* @throws IllegalStateException if invoked on a {@link #close() closed} pool
* @throws Exception when the {@link #getFactory() factory} has a problem creating or passivating an object.
*/
public synchronized void addObject() throws Exception {
assertOpen();
if (_factory == null) {
throw new IllegalStateException("Cannot add objects without a factory.");
}
Object obj = _factory.makeObject();
boolean success = true;
if(!_factory.validateObject(obj)) {
success = false;
} else {
_factory.passivateObject(obj);
}
boolean shouldDestroy = !success;
if(success) {
_pool.add(new SoftReference(obj, refQueue));
notifyAll(); // _numActive has changed
}
if(shouldDestroy) {
try {
_factory.destroyObject(obj);
} catch(Exception e) {
// ignored
}
}
}
/**
* Returns an approximation not less than the of the number of idle instances in the pool.
*
* @return estimated number of idle instances in the pool
*/
public synchronized int getNumIdle() {
pruneClearedReferences();
return _pool.size();
}
/**
* Return the number of instances currently borrowed from this pool.
*
* @return the number of instances currently borrowed from this pool
*/
public synchronized int getNumActive() {
return _numActive;
}
/**
* Clears any objects sitting idle in the pool.
*/
public synchronized void clear() {
if(null != _factory) {
Iterator iter = _pool.iterator();
while(iter.hasNext()) {
try {
Object obj = ((SoftReference)iter.next()).get();
if(null != obj) {
_factory.destroyObject(obj);
}
} catch(Exception e) {
// ignore error, keep destroying the rest
}
}
}
_pool.clear();
pruneClearedReferences();
}
/**
* <p>Close this pool, and free any resources associated with it. Invokes
* {@link #clear()} to destroy and remove instances in the pool.</p>
*
* <p>Calling {@link #addObject} or {@link #borrowObject} after invoking
* this method on a pool will cause them to throw an
* {@link IllegalStateException}.</p>
*
* @throws Exception never - exceptions clearing the pool are swallowed
*/
public void close() throws Exception {
super.close();
clear();
}
/**
* Sets the {@link PoolableObjectFactory factory} this pool uses
* to create new instances. Trying to change
* the <code>factory</code> while there are borrowed objects will
* throw an {@link IllegalStateException}.
*
* @param factory the {@link PoolableObjectFactory} used to create new instances.
* @throws IllegalStateException when the factory cannot be set at this time
* @deprecated to be removed in pool 2.0
*/
public synchronized void setFactory(PoolableObjectFactory factory) throws IllegalStateException {
assertOpen();
if(0 < getNumActive()) {
throw new IllegalStateException("Objects are already active");
} else {
clear();
_factory = factory;
}
}
/**
* If any idle objects were garbage collected, remove their
* {@link Reference} wrappers from the idle object pool.
*/
private void pruneClearedReferences() {
Reference ref;
while ((ref = refQueue.poll()) != null) {
try {
_pool.remove(ref);
} catch (UnsupportedOperationException uoe) {
// ignored
}
}
}
/**
* Returns the {@link PoolableObjectFactory} used by this pool to create and manage object instances.
*
* @return the factory
* @since 1.5.5
*/
public synchronized PoolableObjectFactory getFactory() {
return _factory;
}
/** My pool. */
private List _pool = null;
/** My {@link PoolableObjectFactory}. */
private PoolableObjectFactory _factory = null;
/**
* Queue of broken references that might be able to be removed from <code>_pool</code>.
* This is used to help {@link #getNumIdle()} be more accurate with minimial
* performance overhead.
*/
private final ReferenceQueue refQueue = new ReferenceQueue();
/** Number of active objects. */
private int _numActive = 0;
}