1 | package org.apache.velocity.util; |
2 | |
3 | /* |
4 | * Copyright 1999-2001,2004 The Apache Software Foundation. |
5 | * |
6 | * Licensed under the Apache License, Version 2.0 (the "License"); |
7 | * you may not use this file except in compliance with the License. |
8 | * You may obtain a copy of the License at |
9 | * |
10 | * http://www.apache.org/licenses/LICENSE-2.0 |
11 | * |
12 | * Unless required by applicable law or agreed to in writing, software |
13 | * distributed under the License is distributed on an "AS IS" BASIS, |
14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15 | * See the License for the specific language governing permissions and |
16 | * limitations under the License. |
17 | */ |
18 | |
19 | /** |
20 | * Simple object pool. Based on ThreadPool and few other classes |
21 | * |
22 | * The pool will ignore overflow and return null if empty. |
23 | * |
24 | * @author Gal Shachor |
25 | * @author Costin |
26 | * @author <a href="mailto:geirm@optonline.net">Geir Magnusson Jr.</a> |
27 | * @version $Id: SimplePool.java,v 1.2.14.1 2004/03/03 23:23:07 geirm Exp $ |
28 | */ |
29 | public final class SimplePool |
30 | { |
31 | /* |
32 | * Where the objects are held. |
33 | */ |
34 | private Object pool[]; |
35 | |
36 | /** |
37 | * max amount of objects to be managed |
38 | * set via CTOR |
39 | */ |
40 | private int max; |
41 | |
42 | /** |
43 | * index of previous to next |
44 | * free slot |
45 | */ |
46 | private int current=-1; |
47 | |
48 | public SimplePool(int max) |
49 | { |
50 | this.max = max; |
51 | pool = new Object[max]; |
52 | } |
53 | |
54 | /** |
55 | * Add the object to the pool, silent nothing if the pool is full |
56 | */ |
57 | public void put(Object o) |
58 | { |
59 | int idx=-1; |
60 | |
61 | synchronized( this ) |
62 | { |
63 | /* |
64 | * if we aren't full |
65 | */ |
66 | |
67 | if( current < max - 1 ) |
68 | { |
69 | /* |
70 | * then increment the |
71 | * current index. |
72 | */ |
73 | idx = ++current; |
74 | } |
75 | |
76 | if( idx >= 0 ) |
77 | { |
78 | pool[idx] = o; |
79 | } |
80 | } |
81 | } |
82 | |
83 | /** |
84 | * Get an object from the pool, null if the pool is empty. |
85 | */ |
86 | public Object get() |
87 | { |
88 | int idx = -1; |
89 | |
90 | synchronized( this ) |
91 | { |
92 | /* |
93 | * if we have any in the pool |
94 | */ |
95 | if( current >= 0 ) |
96 | { |
97 | /* |
98 | * take one out, so to speak - |
99 | * separate the two operations |
100 | * to make it clear that you |
101 | * don't want idx = --current; :) |
102 | */ |
103 | |
104 | idx = current; |
105 | current--; |
106 | |
107 | /* |
108 | * and since current was >= 0 |
109 | * to get in here, idx must be as well |
110 | * so save the if() opration |
111 | */ |
112 | |
113 | return pool[idx]; |
114 | } |
115 | } |
116 | |
117 | return null; |
118 | } |
119 | |
120 | /** Return the size of the pool |
121 | */ |
122 | public int getMax() |
123 | { |
124 | return max; |
125 | } |
126 | } |