forked from bvwells/go-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathobject_pool.go
48 lines (43 loc) · 1.01 KB
/
object_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
package creational
import (
"sync"
)
// Pool represents the pool of objects to use.
type Pool struct {
sync.Mutex
inuse []interface{}
available []interface{}
new func() interface{}
}
// NewPool creates a new pool.
func NewPool(new func() interface{}) *Pool {
return &Pool{new: new}
}
// Acquire acquires a new PoolObject to use from the pool.
// Here acquire creates a new instance of a PoolObject if none available.
func (p *Pool) Acquire() interface{} {
p.Lock()
var object interface{}
if len(p.available) != 0 {
object = p.available[0]
p.available = append(p.available[:0], p.available[1:]...)
p.inuse = append(p.inuse, object)
} else {
object = p.new()
p.inuse = append(p.inuse, object)
}
p.Unlock()
return object
}
// Release releases a PoolObject back to the Pool.
func (p *Pool) Release(object interface{}) {
p.Lock()
p.available = append(p.available, object)
for i, v := range p.inuse {
if v == object {
p.inuse = append(p.inuse[:i], p.inuse[i+1:]...)
break
}
}
p.Unlock()
}