forked from jolestar/go-commons-pool
/
pool.go
635 lines (565 loc) · 16.5 KB
/
pool.go
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
package pool
import (
"errors"
"github.com/jolestar/go-commons-pool/collections"
"github.com/jolestar/go-commons-pool/concurrent"
"math"
"sync"
"time"
)
type baseErr struct {
msg string
}
func (this *baseErr) Error() string {
return this.msg
}
type IllegalStatusErr struct {
baseErr
}
func NewIllegalStatusErr(msg string) *IllegalStatusErr {
return &IllegalStatusErr{baseErr{msg}}
}
type NoSuchElementErr struct {
baseErr
}
func NewNoSuchElementErr(msg string) *NoSuchElementErr {
return &NoSuchElementErr{baseErr{msg}}
}
type ObjectPool struct {
AbandonedConfig *AbandonedConfig
Config *ObjectPoolConfig
closed bool
closeLock sync.Mutex
evictionLock sync.Mutex
idleObjects *collections.LinkedBlockingDeque
allObjects *collections.SyncIdentityMap
factory PooledObjectFactory
createCount concurrent.AtomicInteger
destroyedByEvictorCount concurrent.AtomicInteger
destroyedCount concurrent.AtomicInteger
destroyedByBorrowValidationCount concurrent.AtomicInteger
evictor *time.Ticker
evictionIterator collections.Iterator
}
func NewObjectPool(factory PooledObjectFactory, config *ObjectPoolConfig) *ObjectPool {
pool := ObjectPool{factory: factory, Config: config,
idleObjects: collections.NewDeque(math.MaxInt32),
allObjects: collections.NewSyncMap(),
createCount: concurrent.AtomicInteger(0),
destroyedByEvictorCount: concurrent.AtomicInteger(0),
destroyedCount: concurrent.AtomicInteger(0)}
pool.StartEvictor()
return &pool
}
func NewObjectPoolWithDefaultConfig(factory PooledObjectFactory) *ObjectPool {
return NewObjectPool(factory, NewDefaultPoolConfig())
}
// Create an object using the PooledObjectFactory factory, passivate it, and then place it in
// the idle object pool. AddObject is useful for "pre-loading"
// a pool with idle objects. (Optional operation).
func (this *ObjectPool) AddObject() error {
if this.IsClosed() {
return NewIllegalStatusErr("Pool not open")
}
if this.factory == nil {
return NewIllegalStatusErr("Cannot add objects without a factory.")
}
this.addIdleObject(this.create())
return nil
}
func (this *ObjectPool) addIdleObject(p *PooledObject) {
if p != nil {
this.factory.PassivateObject(p)
if this.Config.Lifo {
this.idleObjects.AddFirst(p)
} else {
this.idleObjects.AddLast(p)
}
}
}
//Obtains an instance from this pool.
//
// Instances returned from this method will have been either newly created
// with PooledObjectFactory.MakeObject or will be a previously
// idle object and have been activated with
// PooledObjectFactory.ActivateObject and then validated with
// PooledObjectFactory.ValidateObject.
//
// By contract, clients must return the borrowed instance
// using ReturnObject, InvalidateObject
func (this *ObjectPool) BorrowObject() (interface{}, error) {
return this.borrowObject(this.Config.MaxWaitMillis)
}
//Return the number of instances currently idle in this pool. This may be
//considered an approximation of the number of objects that can be
//BorrowObject borrowed without creating any new instances.
func (this *ObjectPool) GetNumIdle() int {
return this.idleObjects.Size()
}
//Return the number of instances currently borrowed from this pool.
func (this *ObjectPool) GetNumActive() int {
return this.allObjects.Size() - this.idleObjects.Size()
}
func (this *ObjectPool) GetDestroyedCount() int {
return int(this.destroyedCount.Get())
}
func (this *ObjectPool) GetDestroyedByBorrowValidationCount() int {
return int(this.destroyedByBorrowValidationCount.Get())
}
func (this *ObjectPool) removeAbandoned(config *AbandonedConfig) {
// Generate a list of abandoned objects to remove
now := currentTimeMillis()
timeout := now - int64((config.RemoveAbandonedTimeout * 1000))
var remove []PooledObject
objects := this.allObjects.Values()
for _, o := range objects {
pooledObject := o.(PooledObject)
pooledObject.lock.Lock()
if pooledObject.state == ALLOCATED &&
pooledObject.GetLastUsedTime() <= timeout {
pooledObject.markAbandoned()
remove = append(remove, pooledObject)
}
pooledObject.lock.Unlock()
}
// Now remove the abandoned objects
for _, pooledObject := range remove {
//if (config.getLogAbandoned()) {
//pooledObject.printStackTrace(ac.getLogWriter());
//}
this.InvalidateObject(pooledObject.Object)
}
}
func (this *ObjectPool) create() *PooledObject {
localMaxTotal := this.Config.MaxTotal
newCreateCount := this.createCount.IncrementAndGet()
if localMaxTotal > -1 && int(newCreateCount) > localMaxTotal ||
newCreateCount >= math.MaxInt32 {
this.createCount.DecrementAndGet()
return nil
}
p, e := this.factory.MakeObject()
if e != nil {
this.createCount.DecrementAndGet()
//return error ?
return nil
}
// ac := this.abandonedConfig;
// if (ac != null && ac.getLogAbandoned()) {
// p.setLogAbandoned(true);
// }
this.allObjects.Put(p.Object, p)
return p
}
func (this *ObjectPool) destroy(toDestroy *PooledObject) {
this.doDestroy(toDestroy, false)
}
func (this *ObjectPool) doDestroy(toDestroy *PooledObject, inLock bool) {
//golang has not recursive lock, so ...
if inLock {
toDestroy.invalidate()
} else {
toDestroy.Invalidate()
}
this.idleObjects.RemoveFirstOccurrence(toDestroy)
this.allObjects.Remove(toDestroy.Object)
this.factory.DestroyObject(toDestroy)
this.destroyedCount.IncrementAndGet()
this.createCount.DecrementAndGet()
}
func (this *ObjectPool) updateStatsBorrow(object *PooledObject, timeMillis int64) {
//TODO
}
func (this *ObjectPool) updateStatsReturn(activeTime int64) {
//TODO
//returnedCount.incrementAndGet();
//activeTimes.add(activeTime);
}
func (this *ObjectPool) borrowObject(borrowMaxWaitMillis int64) (interface{}, error) {
if this.IsClosed() {
return nil, NewIllegalStatusErr("Pool not open")
}
ac := this.AbandonedConfig
if ac != nil && ac.RemoveAbandonedOnBorrow &&
(this.GetNumIdle() < 2) &&
(this.GetNumActive() > this.Config.MaxTotal-3) {
this.removeAbandoned(ac)
}
var p *PooledObject
// Get local copy of current config so it is consistent for entire
// method execution
blockWhenExhausted := this.Config.BlockWhenExhausted
var create bool
waitTime := currentTimeMillis()
var ok bool
for p == nil {
create = false
if blockWhenExhausted {
p, ok = this.idleObjects.PollFirst().(*PooledObject)
if !ok {
p = this.create()
if p != nil {
create = true
ok = true
}
}
if p == nil {
if borrowMaxWaitMillis < 0 {
obj, err := this.idleObjects.TakeFirst()
if err != nil {
return nil, err
}
p, ok = obj.(*PooledObject)
} else {
obj, err := this.idleObjects.PollFirstWithTimeout(time.Duration(borrowMaxWaitMillis) * time.Millisecond)
if err != nil {
return nil, err
}
p, ok = obj.(*PooledObject)
}
}
if !ok {
return nil, NewNoSuchElementErr("Timeout waiting for idle object")
}
if !p.Allocate() {
p = nil
}
} else {
p, ok = this.idleObjects.PollFirst().(*PooledObject)
if !ok {
p = this.create()
if p != nil {
create = true
}
}
if p == nil {
return nil, NewNoSuchElementErr("Pool exhausted")
}
if !p.Allocate() {
p = nil
}
}
if p != nil {
e := this.factory.ActivateObject(p)
if e != nil {
this.destroy(p)
p = nil
if create {
return nil, NewNoSuchElementErr("Unable to activate object")
}
}
}
if p != nil && (this.Config.TestOnBorrow || create && this.Config.TestOnCreate) {
validate := this.factory.ValidateObject(p)
if !validate {
this.destroy(p)
this.destroyedByBorrowValidationCount.IncrementAndGet()
p = nil
if create {
return nil, NewNoSuchElementErr("Unable to validate object")
}
}
}
}
this.updateStatsBorrow(p, currentTimeMillis()-waitTime)
return p.Object, nil
}
func (this *ObjectPool) isAbandonedConfig() bool {
return this.AbandonedConfig != nil
}
func (this *ObjectPool) ensureIdle(idleCount int, always bool) {
if idleCount < 1 || this.IsClosed() || (!always && !this.idleObjects.HasTakeWaiters()) {
return
}
for this.idleObjects.Size() < idleCount {
p := this.create()
if p == nil {
// Can't create objects, no reason to think another call to
// create will work. Give up.
break
}
if this.Config.Lifo {
this.idleObjects.AddFirst(p)
} else {
this.idleObjects.AddLast(p)
}
}
if this.IsClosed() {
// Pool closed while object was being added to idle objects.
// Make sure the returned object is destroyed rather than left
// in the idle object pool (which would effectively be a leak)
this.Clear()
}
}
func (this *ObjectPool) IsClosed() bool {
this.closeLock.Lock()
defer this.closeLock.Unlock()
// in java commons pool, closed is volatile, golang has not volatile, so use mutex to avoid data race
return this.closed
}
// Return an instance to the pool. By contract, object
// must have been obtained using BorrowObject()
func (this *ObjectPool) ReturnObject(object interface{}) error {
if object == nil {
return errors.New("object is nil.")
}
p, ok := this.allObjects.Get(object).(*PooledObject)
if !ok {
if !this.isAbandonedConfig() {
return NewIllegalStatusErr(
"Returned object not currently part of this pool")
}
return nil // Object was abandoned and removed
}
p.lock.Lock()
state := p.state
if state != ALLOCATED {
p.lock.Unlock()
return NewIllegalStatusErr(
"Object has already been returned to this pool or is invalid")
}
//use unlock method markReturning() not MarkReturning
// because go lock is not recursive
p.markReturning() // Keep from being marked abandoned
p.lock.Unlock()
activeTime := p.GetActiveTimeMillis()
if this.Config.TestOnReturn {
if !this.factory.ValidateObject(p) {
this.destroy(p)
this.ensureIdle(1, false)
this.updateStatsReturn(activeTime)
// swallowException(e);
return nil
}
}
err := this.factory.PassivateObject(p)
if err != nil {
//swallowException(e1);
this.destroy(p)
this.ensureIdle(1, false)
this.updateStatsReturn(activeTime)
// swallowException(e);
return nil
}
if !p.Deallocate() {
return NewIllegalStatusErr("Object has already been returned to this pool or is invalid")
}
maxIdleSave := this.Config.MaxIdle
if this.IsClosed() || maxIdleSave > -1 && maxIdleSave <= this.idleObjects.Size() {
this.destroy(p)
} else {
if this.Config.Lifo {
this.idleObjects.AddFirst(p)
} else {
this.idleObjects.AddLast(p)
}
if this.IsClosed() {
// Pool closed while object was being added to idle objects.
// Make sure the returned object is destroyed rather than left
// in the idle object pool (which would effectively be a leak)
this.Clear()
}
}
this.updateStatsReturn(activeTime)
return nil
}
//Clears any objects sitting idle in the pool, releasing any associated
//resources (optional operation). Idle objects cleared must be
//PooledObjectFactory.DestroyObject(PooledObject) .
func (this *ObjectPool) Clear() {
p, ok := this.idleObjects.PollFirst().(*PooledObject)
for ok {
this.destroy(p)
p, ok = this.idleObjects.PollFirst().(*PooledObject)
}
}
// Invalidates an object from the pool.
//
// By contract, object must have been obtained
// using BorrowObject.
//
// This method should be used when an object that has been borrowed is
// determined (due to an exception or other problem) to be invalid.
func (this *ObjectPool) InvalidateObject(object interface{}) error {
p, ok := this.allObjects.Get(object).(*PooledObject)
if !ok {
if this.isAbandonedConfig() {
return nil
} else {
return NewIllegalStatusErr(
"Invalidated object not currently part of this pool")
}
}
p.lock.Lock()
if p.state != INVALID {
this.doDestroy(p, true)
}
p.lock.Unlock()
this.ensureIdle(1, false)
return nil
}
//Close this pool, and free any resources associated with it.
func (this *ObjectPool) Close() {
if this.IsClosed() {
return
}
this.closeLock.Lock()
defer this.closeLock.Unlock()
if this.closed {
return
}
// Stop the evictor before the pool is closed since evict() calls
// assertOpen()
this.startEvictor(-1)
this.closed = true
// This clear removes any idle objects
this.Clear()
// Release any threads that were waiting for an object
this.idleObjects.InterruptTakeWaiters()
}
//if ObjectPool.Config.TimeBetweenEvictionRunsMillis change, should call this method to let it to take effect.
func (this *ObjectPool) StartEvictor() {
this.startEvictor(this.Config.TimeBetweenEvictionRunsMillis)
}
func (this *ObjectPool) startEvictor(delay int64) {
this.evictionLock.Lock()
defer this.evictionLock.Unlock()
if nil != this.evictor {
this.evictor.Stop()
this.evictor = nil
this.evictionIterator = nil
}
if delay > 0 {
this.evictor = time.NewTicker(time.Duration(delay) * time.Millisecond)
go func() {
for _ = range this.evictor.C {
this.evict()
this.ensureMinIdle()
}
}()
}
}
func (this *ObjectPool) getEvictionPolicy() EvictionPolicy {
evictionPolicy := GetEvictionPolicy(this.Config.EvictionPolicyName)
if evictionPolicy == nil {
evictionPolicy = GetEvictionPolicy(DEFAULT_EVICTION_POLICY_NAME)
}
return evictionPolicy
}
func (this *ObjectPool) getNumTests() int {
numTestsPerEvictionRun := this.Config.NumTestsPerEvictionRun
if numTestsPerEvictionRun >= 0 {
if numTestsPerEvictionRun < this.idleObjects.Size() {
return numTestsPerEvictionRun
} else {
return this.idleObjects.Size()
}
}
return int((math.Ceil(float64(this.idleObjects.Size()) / math.Abs(float64(numTestsPerEvictionRun)))))
}
func (this *ObjectPool) EvictionIterator() collections.Iterator {
if this.Config.Lifo {
return this.idleObjects.DescendingIterator()
} else {
return this.idleObjects.Iterator()
}
}
func (this *ObjectPool) getMinIdle() int {
maxIdleSave := this.Config.MaxIdle
if this.Config.MinIdle > maxIdleSave {
return maxIdleSave
}
return this.Config.MinIdle
}
func (this *ObjectPool) evict() {
defer func() {
ac := this.AbandonedConfig
if ac != nil && ac.RemoveAbandonedOnMaintenance {
this.removeAbandoned(ac)
}
}()
if this.idleObjects.Size() == 0 {
return
}
var underTest *PooledObject
evictionPolicy := this.getEvictionPolicy()
this.evictionLock.Lock()
defer this.evictionLock.Unlock()
evictionConfig := EvictionConfig{
IdleEvictTime: this.Config.MinEvictableIdleTimeMillis,
IdleSoftEvictTime: this.Config.SoftMinEvictableIdleTimeMillis,
MinIdle: this.Config.MinIdle}
testWhileIdle := this.Config.TestWhileIdle
for i, m := 0, this.getNumTests(); i < m; i++ {
if this.evictionIterator == nil || !this.evictionIterator.HasNext() {
this.evictionIterator = this.EvictionIterator()
}
if !this.evictionIterator.HasNext() {
// Pool exhausted, nothing to do here
return
}
underTest = this.evictionIterator.Next().(*PooledObject)
if underTest == nil {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--
this.evictionIterator = nil
continue
}
if !underTest.StartEvictionTest() {
// Object was borrowed in another thread
// Don't count this as an eviction test so reduce i;
i--
continue
}
// User provided eviction policy could throw all sorts of
// crazy exceptions. Protect against such an exception
// killing the eviction thread.
evict := evictionPolicy.Evict(&evictionConfig, underTest, this.idleObjects.Size())
if evict {
this.destroy(underTest)
this.destroyedByEvictorCount.IncrementAndGet()
} else {
var active bool = false
if testWhileIdle {
err := this.factory.ActivateObject(underTest)
if err == nil {
active = true
} else {
this.destroy(underTest)
this.destroyedByEvictorCount.IncrementAndGet()
}
if active {
if !this.factory.ValidateObject(underTest) {
this.destroy(underTest)
this.destroyedByEvictorCount.IncrementAndGet()
} else {
err := this.factory.PassivateObject(underTest)
if err != nil {
this.destroy(underTest)
this.destroyedByEvictorCount.IncrementAndGet()
}
}
}
}
if !underTest.EndEvictionTest(this.idleObjects) {
// TODO - May need to add code here once additional
// states are used
}
}
}
}
func (this *ObjectPool) ensureMinIdle() {
this.ensureIdle(this.getMinIdle(), true)
}
func (this *ObjectPool) preparePool() {
if this.getMinIdle() < 1 {
return
}
this.ensureMinIdle()
}
func Prefill(pool *ObjectPool, count int) {
for i := 0; i < count; i++ {
pool.AddObject()
}
}