-
Notifications
You must be signed in to change notification settings - Fork 0
/
obj_pool.go
85 lines (72 loc) · 1.25 KB
/
obj_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
package utils
import (
"sync"
. "github.com/aywfelix/felixgo/container/list"
)
type IObjPool interface {
GetObj() interface{}
FreeObj(obj interface{})
UseCount() int
Count() int
Clear()
}
type ObjPool struct {
size int
count int
deque *Deque
New func() interface{}
sync.RWMutex
incrStep int
}
const incrStep = 15
func NewObjPool(newFunc func() interface{}, defaultCount int, incrStep int) *ObjPool {
pool := &ObjPool{
size: 0,
count: defaultCount,
deque: NewDeque(),
New: newFunc,
incrStep: incrStep,
}
for i := 0; i < defaultCount; i++ {
o := pool.New()
pool.deque.PushBack(o)
}
return pool
}
func (p *ObjPool) expand() {
if p.New == nil {
return
}
p.count += incrStep
for i := 0; i < incrStep; i++ {
o := p.New()
p.deque.PushBack(o)
}
}
func (p *ObjPool) GetObj() interface{} {
if p.deque.Empty() {
p.Lock()
p.expand()
defer p.Unlock()
}
return p.deque.PopFront()
}
func (p *ObjPool) FreeObj(obj interface{}) {
if obj != nil {
p.deque.PushBack(obj)
}
}
func (p *ObjPool) UseCount() int {
p.Lock()
defer p.Unlock()
return p.count - p.deque.Size()
}
func (p *ObjPool) Count() int {
p.RLock()
defer p.RUnlock()
return p.count
}
func (p *ObjPool) Clear() {
p.New = nil
p.deque = nil
}