-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpool.go
68 lines (59 loc) · 1.47 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
// Copyright (c) Jeevanandam M. (https://github.com/jeevatkm)
// go-aah/pool source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
// Package pool provides channel based bounded pooling capabilities.
package pool
// Version no. of aah framework pool library
const Version = "0.3"
// Pool holds the bounded channel for interface{}.
type Pool struct {
// c bounded channel
c chan interface{}
// New optionally specifies a function to generate
// a value when Get would otherwise return nil.
// It may not be changed concurrently with calls to Get.
New func() interface{}
}
// NewPool method creates a new Pool bounded to the given size.
func NewPool(size int, fn func() interface{}) (p *Pool) {
return &Pool{
c: make(chan interface{}, size),
New: fn,
}
}
// Get method gets a value from the Pool, or creates a new one if none are
// available in the pool.
func (p *Pool) Get() (v interface{}) {
select {
case v = <-p.c:
// reuse from pool
default:
// create new one
if p.New != nil {
v = p.New()
}
}
return
}
// Put method returns given value into Pool.
func (p *Pool) Put(v interface{}) {
select {
case p.c <- v:
default: // Discard the value if the pool is full.
}
}
// Count method returns current count of pool.
func (p *Pool) Count() int {
return len(p.c)
}
// Drain method drains all the values for the channel
func (p *Pool) Drain() {
for {
select {
case <-p.c:
// draining it
default:
return
}
}
}