This repository has been archived by the owner on Dec 25, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
ObjectPool.ts
235 lines (204 loc) · 4.82 KB
/
ObjectPool.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
/*!
* @author electricessence / https://github.com/electricessence/
* Licensing: MIT https://github.com/electricessence/TypeScript.NET/blob/master/LICENSE.md
* Based upon ObjectPool from Parallel Extension Extras and other ObjectPool implementations.
* Uses .add(T) and .take():T
*/
import {dispose} from "./dispose";
import {DisposableBase} from "./DisposableBase";
import {TaskHandler} from "../Threading/Tasks/TaskHandler";
import {ArgumentOutOfRangeException} from "../Exceptions/ArgumentOutOfRangeException";
import {ArgumentException} from "../Exceptions/ArgumentException";
import __extendsImport from "../../extends";
// noinspection JSUnusedLocalSymbols
const __extends = __extendsImport;
const
OBJECT_POOL = "ObjectPool",
_MAX_SIZE = "_maxSize",
ABSOLUTE_MAX_SIZE = 65536,
MUST_BE_GT1 = "Must be at valid number least 1.",
MUST_BE_LTM = `Must be less than or equal to ${ABSOLUTE_MAX_SIZE}.`;
export class ObjectPool<T> extends DisposableBase
{
private _pool:T[];
private _trimmer:TaskHandler;
private _flusher:TaskHandler;
private _autoFlusher:TaskHandler;
/**
* A transient amount of object to exist over _maxSize until trim() is called.
* But any added objects over _localAbsMaxSize will be disposed immediately.
*/
private _localAbsMaxSize:number;
/**
* By default will clear after 5 seconds of non-use.
*/
autoClearTimeout:number = 5000;
constructor(
private _maxSize:number,
private _generator?:(...args:any[])=>T,
private _recycler?:(o:T)=>void)
{
super(OBJECT_POOL);
if(isNaN(_maxSize) || _maxSize<1)
throw new ArgumentOutOfRangeException(_MAX_SIZE, _maxSize, MUST_BE_GT1);
if(_maxSize>ABSOLUTE_MAX_SIZE)
throw new ArgumentOutOfRangeException(_MAX_SIZE, _maxSize, MUST_BE_LTM);
this._localAbsMaxSize = Math.min(_maxSize*2, ABSOLUTE_MAX_SIZE);
this._pool = [];
this._trimmer = new TaskHandler(()=>this._trim());
const clear = () => this._clear();
this._flusher = new TaskHandler(clear);
this._autoFlusher = new TaskHandler(clear);
}
/**
* Defines the maximum at which trimming should allow.
* @returns {number}
*/
get maxSize():number
{
return this._maxSize;
}
/**
* Current number of objects in pool.
* @returns {number}
*/
get count():number
{
const p = this._pool;
return p ? p.length : 0;
}
protected _trim():void
{
const pool = this._pool;
while(pool.length>this._maxSize)
{
dispose.single(<any>pool.pop(),true);
}
}
/**
* Will trim ensure the pool is less than the maxSize.
* @param defer A delay before trimming. Will be overridden by later calls.
*/
trim(defer?:number):void
{
this.throwIfDisposed();
this._trimmer.start(defer);
}
protected _clear():void
{
const _ = this;
const p = _._pool;
_._trimmer.cancel();
_._flusher.cancel();
_._autoFlusher.cancel();
dispose.these.noCopy(<any>p, true);
p.length = 0;
}
/**
* Will clear out the pool.
* Cancels any scheduled trims when executed.
* @param defer A delay before clearing. Will be overridden by later calls.
*/
clear(defer?:number):void
{
this.throwIfDisposed();
this._flusher.start(defer);
}
toArrayAndClear():T[]
{
this.throwIfDisposed();
this._trimmer.cancel();
this._flusher.cancel();
const p = this._pool;
this._pool = [];
return p;
}
/**
* Shortcut for toArrayAndClear();
*/
dump():T[]
{
return this.toArrayAndClear();
}
protected _onDispose():void
{
super._onDispose();
const _:any = this;
_._generator = null;
_._recycler = null;
dispose(
_._trimmer,
_._flusher,
_._autoFlusher
);
_._trimmer = null;
_._flusher = null;
_._autoFlusher = null;
_._pool.length = 0;
_._pool = null;
}
extendAutoClear():void
{
const _ = this;
_.throwIfDisposed();
const t = _.autoClearTimeout;
if(isFinite(t) && !_._autoFlusher.isScheduled)
_._autoFlusher.start(t);
}
add(o:T):void
{
const _ = this;
_.throwIfDisposed();
if(_._pool.length>=_._localAbsMaxSize)
{
// Getting too big, dispose immediately...
dispose(<any>o);
}
else
{
if(_._recycler) _._recycler(o);
_._pool.push(o);
const m = _._maxSize;
if(m<ABSOLUTE_MAX_SIZE && _._pool.length>m)
_._trimmer.start(500);
}
_.extendAutoClear();
}
private _onTaken():void
{
const _ = this, len = _._pool.length;
if(len<=_._maxSize)
_._trimmer.cancel();
if(len)
_.extendAutoClear();
}
tryTake():T|undefined
{
const _ = this;
_.throwIfDisposed();
try
{
return _._pool.pop();
}
finally
{
_._onTaken();
}
}
take(factory?:()=>T):T
{
const _ = this;
_.throwIfDisposed();
if(!_._generator && !factory)
throw new ArgumentException('factory', "Must provide a factory if on was not provided at construction time.");
try
{
return _._pool.pop() || factory && factory() || _._generator!();
}
finally
{
_._onTaken();
}
}
}
export default ObjectPool;