-
Notifications
You must be signed in to change notification settings - Fork 5
/
pool.go
65 lines (54 loc) · 1.05 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
package pool
import (
"container/list"
"errors"
"log"
"strconv"
)
type PoolObject struct {
id int
}
type Pool struct {
idle *list.List
active *list.List
}
func InitPool() Pool {
pool := &Pool{
list.New(),
list.New(),
}
return *pool
}
func (p *Pool) Borrow() (*PoolObject, error) {
if p.idle.Len() > 0 {
for e, i := p.idle.Front(), 0; e != nil; e, i = e.Next(), i+1 {
if i == 0 {
object := e.Value.(PoolObject)
return &object, nil
}
}
}
log.Println(strconv.Itoa(p.active.Len()))
if p.NumberOfObjectsInPool() >= 3 {
return nil, errors.New("...")
}
object := PoolObject{p.NumberOfObjectsInPool() + 1}
p.active.PushBack(object)
return &object, nil
}
func (p *Pool) Receive(object PoolObject) {
p.idle.PushBack(object)
for e := p.active.Front(); e != nil; e = e.Next() {
p.active.Remove(e)
return
}
}
func (p *Pool) NumberOfObjectsInPool() int {
return p.active.Len() + p.idle.Len()
}
func (p *Pool) NumberOfActiveObjects() int {
return p.active.Len()
}
func (p *Pool) NumberOfIdleObjects() int {
return p.idle.Len()
}