forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pool.go
108 lines (91 loc) · 1.85 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
package syncx
import (
"sync"
"time"
"github.com/xiaoshouchen/go-zero/core/timex"
)
type (
// PoolOption defines the method to customize a Pool.
PoolOption func(*Pool)
node struct {
item interface{}
next *node
lastUsed time.Duration
}
// A Pool is used to pool resources.
// The difference between sync.Pool is that:
// 1. the limit of the resources
// 2. max age of the resources can be set
// 3. the method to destroy resources can be customized
Pool struct {
limit int
created int
maxAge time.Duration
lock sync.Locker
cond *sync.Cond
head *node
create func() interface{}
destroy func(interface{})
}
)
// NewPool returns a Pool.
func NewPool(n int, create func() interface{}, destroy func(interface{}), opts ...PoolOption) *Pool {
if n <= 0 {
panic("pool size can't be negative or zero")
}
lock := new(sync.Mutex)
pool := &Pool{
limit: n,
lock: lock,
cond: sync.NewCond(lock),
create: create,
destroy: destroy,
}
for _, opt := range opts {
opt(pool)
}
return pool
}
// Get gets a resource.
func (p *Pool) Get() interface{} {
p.lock.Lock()
defer p.lock.Unlock()
for {
if p.head != nil {
head := p.head
p.head = head.next
if p.maxAge > 0 && head.lastUsed+p.maxAge < timex.Now() {
p.created--
p.destroy(head.item)
continue
} else {
return head.item
}
}
if p.created < p.limit {
p.created++
return p.create()
}
p.cond.Wait()
}
}
// Put puts a resource back.
func (p *Pool) Put(x interface{}) {
if x == nil {
return
}
p.lock.Lock()
defer p.lock.Unlock()
p.head = &node{
item: x,
next: p.head,
lastUsed: timex.Now(),
}
p.cond.Signal()
}
// WithMaxAge returns a function to customize a Pool with given max age.
func WithMaxAge(duration time.Duration) PoolOption {
return func(pool *Pool) {
pool.maxAge = duration
}
}