freelist.js 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2015 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 Simple freelist.
  16. *
  17. * An anterative to goog.structs.SimplePool, it imposes the requirement that the
  18. * objects in the list contain a "next" property that can be used to maintain
  19. * the pool.
  20. */
  21. goog.provide('goog.async.FreeList');
  22. /**
  23. * @template ITEM
  24. */
  25. goog.async.FreeList = goog.defineClass(null, {
  26. /**
  27. * @param {function():ITEM} create
  28. * @param {function(ITEM):void} reset
  29. * @param {number} limit
  30. */
  31. constructor: function(create, reset, limit) {
  32. /** @private @const {number} */
  33. this.limit_ = limit;
  34. /** @private @const {function()} */
  35. this.create_ = create;
  36. /** @private @const {function(ITEM):void} */
  37. this.reset_ = reset;
  38. /** @private {number} */
  39. this.occupants_ = 0;
  40. /** @private {ITEM} */
  41. this.head_ = null;
  42. },
  43. /**
  44. * @return {ITEM}
  45. */
  46. get: function() {
  47. var item;
  48. if (this.occupants_ > 0) {
  49. this.occupants_--;
  50. item = this.head_;
  51. this.head_ = item.next;
  52. item.next = null;
  53. } else {
  54. item = this.create_();
  55. }
  56. return item;
  57. },
  58. /**
  59. * @param {ITEM} item An item available for possible future reuse.
  60. */
  61. put: function(item) {
  62. this.reset_(item);
  63. if (this.occupants_ < this.limit_) {
  64. this.occupants_++;
  65. item.next = this.head_;
  66. this.head_ = item;
  67. }
  68. },
  69. /**
  70. * Visible for testing.
  71. * @package
  72. * @return {number}
  73. */
  74. occupants: function() { return this.occupants_; }
  75. });