-
Notifications
You must be signed in to change notification settings - Fork 11
/
pool.go
43 lines (38 loc) · 853 Bytes
/
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
package pool
import (
"github.com/ngaut/logging"
"sync"
)
// A cache holds a set of reusable objects.
// The slice is a stack (LIFO).
// If more are needed, the cache creates them by calling new.
type Cache struct {
mu sync.Mutex
name string
saved []interface{}
new func() interface{}
}
func (c *Cache) Put(x interface{}) {
c.mu.Lock()
if len(c.saved) < cap(c.saved) {
c.saved = append(c.saved, x)
} else {
logging.Warning(c.name, "is full, you may need to increase pool size")
}
c.mu.Unlock()
}
func (c *Cache) Get() interface{} {
c.mu.Lock()
n := len(c.saved)
if n == 0 {
c.mu.Unlock()
return c.new()
}
x := c.saved[n-1]
c.saved = c.saved[0 : n-1]
c.mu.Unlock()
return x
}
func NewCache(name string, cap int, f func() interface{}) *Cache {
return &Cache{name: name, saved: make([]interface{}, 0, cap), new: f}
}