pool.js 10.0 KB

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