KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > ibatis > common > util > ThrottledPool


1 /*
2  * Copyright 2004 Clinton Begin
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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 com.ibatis.common.exception.NestedRuntimeException;
19
20 import java.util.List JavaDoc;
21 import java.util.Collections JavaDoc;
22 import java.util.ArrayList JavaDoc;
23
24 /**
25  * This is a pool of Throttle objects (!)
26  */

27 public class ThrottledPool {
28
29  private Throttle throttle;
30
31   private Class JavaDoc type;
32   private List JavaDoc pool;
33
34   /**
35    * Create a ThrottledPool for a Class
36    * @param type - the type of objects being managed
37    * @param size - the size of the pool
38    */

39   public ThrottledPool(Class JavaDoc type, int size) {
40     try {
41       this.throttle = new Throttle(size);
42       this.type = type;
43       this.pool = Collections.synchronizedList(new ArrayList JavaDoc(size));
44       for (int i=0; i < size; i++) {
45         this.pool.add(type.newInstance());
46       }
47     } catch (Exception JavaDoc e) {
48       throw new NestedRuntimeException("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 JavaDoc pop() {
57     Object JavaDoc o = null;
58     while (o == null) {
59       try {
60         throttle.increment();
61         o = pool.remove(0);
62       } catch (Exception JavaDoc e) {
63         // thread collision detected, retry
64
}
65     }
66     return o;
67   }
68
69   /**
70    * Push an object onto the pool
71    * @param o - the object to put into the pool
72    */

73   public void push(Object JavaDoc o) {
74     if (o != null && o.getClass() == type) pool.add(o);
75     throttle.decrement();
76   }
77
78 }
79
Popular Tags