01: /*
02: * Copyright 2004 Clinton Begin
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package com.ibatis.common.util;
17:
18: import java.util.List;
19: import java.util.Collections;
20: import java.util.ArrayList;
21:
22: /**
23: * This is a pool of Throttle objects (!)
24: */
25: public class ThrottledPool {
26:
27: private Throttle throttle;
28:
29: private Class type;
30: private List pool;
31:
32: /**
33: * Create a ThrottledPool for a Class
34: * @param type - the type of objects being managed
35: * @param size - the size of the pool
36: */
37: public ThrottledPool(Class type, int size) {
38: try {
39: this .throttle = new Throttle(size);
40: this .type = type;
41: this .pool = Collections
42: .synchronizedList(new ArrayList(size));
43: for (int i = 0; i < size; i++) {
44: this .pool.add(type.newInstance());
45: }
46: } catch (Exception e) {
47: throw new RuntimeException(
48: "Error instantiating class. Cause: " + e, e);
49: }
50: }
51:
52: /**
53: * Pop an object from the pool
54: * @return - the Object
55: */
56: public Object pop() {
57: throttle.increment();
58: return pool.remove(0);
59: }
60:
61: /**
62: * Push an object onto the pool
63: * @param o - the object to put into the pool
64: */
65: public void push(Object o) {
66: if (o != null && o.getClass() == type) {
67: pool.add(o);
68: throttle.decrement();
69: }
70: }
71:
72: }
|