Debian Codegraph @

closure-library/closure/goog/structs/pool.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Datastructure: Pool.
17 *
18 *
19 * A generic class for handling pools of objects.
20 * When an object is released, it is attempted to be reused.
21 */
22
23
24 goog.provide('goog.structs.Pool');
25
26 goog.require('goog.Disposable');
27 goog.require('goog.structs.Queue');
28 goog.require('goog.structs.Set');
29
30
31
32 /**
33 * A generic pool class. If min is greater than max, an error is thrown.
34 * @param {number=} opt_minCount Min. number of objects (Default: 0).
35 * @param {number=} opt_maxCount Max. number of objects (Default: 10).
36 * @constructor
37 * @extends {goog.Disposable}
38 * @template T
39 */
40 goog.structs.Pool = function(opt_minCount, opt_maxCount) {
41 goog.Disposable.call(this);
42
43 /**
44 * Minimum number of objects allowed
45 * @private {number}
46 */
47 this.minCount_ = opt_minCount || 0;
48
49 /**
50 * Maximum number of objects allowed
51 * @private {number}
52 */
53 this.maxCount_ = opt_maxCount || 10;
54
55 // Make sure that the max and min constraints are valid.
56 if (this.minCount_ > this.maxCount_) {
57 throw new Error(goog.structs.Pool.ERROR_MIN_MAX_);
58 }
59
60 /**
61 * Set used to store objects that are currently in the pool and available
62 * to be used.
63 * @private {goog.structs.Queue<T>}
64 */
65 this.freeQueue_ = new goog.structs.Queue();
66
67 /**
68 * Set used to store objects that are currently in the pool and in use.
69 * @private {goog.structs.Set<T>}
70 */
71 this.inUseSet_ = new goog.structs.Set();
72
73 /**
74 * The minimum delay between objects being made available, in milliseconds. If
75 * this is 0, no minimum delay is enforced.
76 * @protected {number}
77 */
78 this.delay = 0;
79
80 /**
81 * The time of the last object being made available, in milliseconds since the
82 * epoch (i.e., the result of Date#toTime). If this is null, no access has
83 * occurred yet.
84 * @protected {number?}
85 */
86 this.lastAccess = null;
87
88 // Make sure that the minCount constraint is satisfied.
89 this.adjustForMinMax();
90 };
91 goog.inherits(goog.structs.Pool, goog.Disposable);
92
93
94 /**
95 * Error to throw when the max/min constraint is attempted to be invalidated.
96 * I.e., when it is attempted for maxCount to be less than minCount.
97 * @type {string}
98 * @private
99 */
100 goog.structs.Pool.ERROR_MIN_MAX_ =
101 '[goog.structs.Pool] Min can not be greater than max';
102
103
104 /**
105 * Error to throw when the Pool is attempted to be disposed and it is asked to
106 * make sure that there are no objects that are in use (i.e., haven't been
107 * released).
108 * @type {string}
109 * @private
110 */
111 goog.structs.Pool.ERROR_DISPOSE_UNRELEASED_OBJS_ =
112 '[goog.structs.Pool] Objects not released';
113
114
115 /**
116 * Sets the minimum count of the pool.
117 * If min is greater than the max count of the pool, an error is thrown.
118 * @param {number} min The minimum count of the pool.
119 */
120 goog.structs.Pool.prototype.setMinimumCount = function(min) {
121 // Check count constraints.
122 if (min > this.maxCount_) {
123 throw new Error(goog.structs.Pool.ERROR_MIN_MAX_);
124 }
125 this.minCount_ = min;
126
127 // Adjust the objects in the pool as needed.
128 this.adjustForMinMax();
129 };
130
131
132 /**
133 * Sets the maximum count of the pool.
134 * If max is less than the min count of the pool, an error is thrown.
135 * @param {number} max The maximum count of the pool.
136 */
137 goog.structs.Pool.prototype.setMaximumCount = function(max) {
138 // Check count constraints.
139 if (max < this.minCount_) {
140 throw new Error(goog.structs.Pool.ERROR_MIN_MAX_);
141 }
142 this.maxCount_ = max;
143
144 // Adjust the objects in the pool as needed.
145 this.adjustForMinMax();
146 };
147
148
149 /**
150 * Sets the minimum delay between objects being returned by getObject, in
151 * milliseconds. This defaults to zero, meaning that no minimum delay is
152 * enforced and objects may be used as soon as they're available.
153 * @param {number} delay The minimum delay, in milliseconds.
154 */
155 goog.structs.Pool.prototype.setDelay = function(delay) {
156 this.delay = delay;
157 };
158
159
160 /**
161 * @return {T|undefined} A new object from the pool if there is one available,
162 * otherwise undefined.
163 */
164 goog.structs.Pool.prototype.getObject = function() {
165 var time = goog.now();
166 if (goog.isDefAndNotNull(this.lastAccess) &&
167 time - this.lastAccess < this.delay) {
168 return undefined;
169 }
170
171 var obj = this.removeFreeObject_();
172 if (obj) {
173 this.lastAccess = time;
174 this.inUseSet_.add(obj);
175 }
176
177 return obj;
178 };
179
180
181 /**
182 * Returns an object to the pool of available objects so that it can be reused.
183 * @param {T} obj The object to return to the pool of free objects.
184 * @return {boolean} Whether the object was found in the Pool's set of in-use
185 * objects (in other words, whether any action was taken).
186 */
187 goog.structs.Pool.prototype.releaseObject = function(obj) {
188 if (this.inUseSet_.remove(obj)) {
189 this.addFreeObject(obj);
190 return true;
191 }
192 return false;
193 };
194
195
196 /**
197 * Removes a free object from the collection of objects that are free so that it
198 * can be used.
199 *
200 * NOTE: This method does not mark the returned object as in use.
201 *
202 * @return {T|undefined} The object removed from the free collection, if there
203 * is one available. Otherwise, undefined.
204 * @private
205 */
206 goog.structs.Pool.prototype.removeFreeObject_ = function() {
207 var obj;
208 while (this.getFreeCount() > 0) {
209 obj = this.freeQueue_.dequeue();
210
211 if (!this.objectCanBeReused(obj)) {
212 this.adjustForMinMax();
213 } else {
214 break;
215 }
216 }
217
218 if (!obj && this.getCount() < this.maxCount_) {
219 obj = this.createObject();
220 }
221
222 return obj;
223 };
224
225
226 /**
227 * Adds an object to the collection of objects that are free. If the object can
228 * not be added, then it is disposed.
229 *
230 * @param {T} obj The object to add to collection of free objects.
231 */
232 goog.structs.Pool.prototype.addFreeObject = function(obj) {
233 this.inUseSet_.remove(obj);
234 if (this.objectCanBeReused(obj) && this.getCount() < this.maxCount_) {
235 this.freeQueue_.enqueue(obj);
236 } else {
237 this.disposeObject(obj);
238 }
239 };
240
241
242 /**
243 * Adjusts the objects held in the pool to be within the min/max constraints.
244 *
245 * NOTE: It is possible that the number of objects in the pool will still be
246 * greater than the maximum count of objects allowed. This will be the case
247 * if no more free objects can be disposed of to get below the minimum count
248 * (i.e., all objects are in use).
249 */
250 goog.structs.Pool.prototype.adjustForMinMax = function() {
251 var freeQueue = this.freeQueue_;
252
253 // Make sure the at least the minimum number of objects are created.
254 while (this.getCount() < this.minCount_) {
255 freeQueue.enqueue(this.createObject());
256 }
257
258 // Make sure no more than the maximum number of objects are created.
259 while (this.getCount() > this.maxCount_ && this.getFreeCount() > 0) {
260 this.disposeObject(freeQueue.dequeue());
261 }
262 };
263
264
265 /**
266 * Should be overridden by sub-classes to return an instance of the object type
267 * that is expected in the pool.
268 * @return {T} The created object.
269 */
270 goog.structs.Pool.prototype.createObject = function() {
271 return {};
272 };
273
274
275 /**
276 * Should be overridden to dispose of an object. Default implementation is to
277 * remove all its members, which should render it useless. Calls the object's
278 * {@code dispose()} method, if available.
279 * @param {T} obj The object to dispose.
280 */
281 goog.structs.Pool.prototype.disposeObject = function(obj) {
282 if (typeof obj.dispose == 'function') {
283 obj.dispose();
284 } else {
285 for (var i in obj) {
286 obj[i] = null;
287 }
288 }
289 };
290
291
292 /**
293 * Should be overridden to determine whether an object has become unusable and
294 * should not be returned by getObject(). Calls the object's
295 * {@code canBeReused()} method, if available.
296 * @param {T} obj The object to test.
297 * @return {boolean} Whether the object can be reused.
298 */
299 goog.structs.Pool.prototype.objectCanBeReused = function(obj) {
300 if (typeof obj.canBeReused == 'function') {
301 return obj.canBeReused();
302 }
303 return true;
304 };
305
306
307 /**
308 * Returns true if the given object is in the pool.
309 * @param {T} obj The object to check the pool for.
310 * @return {boolean} Whether the pool contains the object.
311 */
312 goog.structs.Pool.prototype.contains = function(obj) {
313 return this.freeQueue_.contains(obj) || this.inUseSet_.contains(obj);
314 };
315
316
317 /**
318 * Returns the number of objects currently in the pool.
319 * @return {number} Number of objects currently in the pool.
320 */
321 goog.structs.Pool.prototype.getCount = function() {
322 return this.freeQueue_.getCount() + this.inUseSet_.getCount();
323 };
324
325
326 /**
327 * Returns the number of objects currently in use in the pool.
328 * @return {number} Number of objects currently in use in the pool.
329 */
330 goog.structs.Pool.prototype.getInUseCount = function() {
331 return this.inUseSet_.getCount();
332 };
333
334
335 /**
336 * Returns the number of objects currently free in the pool.
337 * @return {number} Number of objects currently free in the pool.
338 */
339 goog.structs.Pool.prototype.getFreeCount = function() {
340 return this.freeQueue_.getCount();
341 };
342
343
344 /**
345 * Determines if the pool contains no objects.
346 * @return {boolean} Whether the pool contains no objects.
347 */
348 goog.structs.Pool.prototype.isEmpty = function() {
349 return this.freeQueue_.isEmpty() && this.inUseSet_.isEmpty();
350 };
351
352
353 /**
354 * Disposes of the pool and all objects currently held in the pool.
355 * @override
356 * @protected
357 */
358 goog.structs.Pool.prototype.disposeInternal = function() {
359 goog.structs.Pool.superClass_.disposeInternal.call(this);
360 if (this.getInUseCount() > 0) {
361 throw new Error(goog.structs.Pool.ERROR_DISPOSE_UNRELEASED_OBJS_);
362 }
363 delete this.inUseSet_;
364
365 // Call disposeObject on each object held by the pool.
366 var freeQueue = this.freeQueue_;
367 while (!freeQueue.isEmpty()) {
368 this.disposeObject(freeQueue.dequeue());
369 }
370 delete this.freeQueue_;
371 };