-
Notifications
You must be signed in to change notification settings - Fork 140
/
object_pool.go
48 lines (42 loc) · 988 Bytes
/
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 object_pool
import (
"fmt"
"sync"
)
/*
The Object Pool Design Pattern is a creational design pattern,
in which a Pool of objects is initialized and created beforehand and kept in a Pool.
As and when needed, a client can request an object from the Pool, use it, and return it to the Pool.
The object in the Pool is never destroyed.
*/
type Pool struct {
idle []IConnection
active []IConnection
capacity int
mulock *sync.Mutex
}
func initPool(conns []IConnection) (*Pool, error) {
if len(conns) == 0 {
return nil, fmt.Errorf("cannot create a pool of 0 length")
}
active := make([]IConnection, 0)
return &Pool{
idle: conns,
active: active,
capacity: len(conns),
mulock: new(sync.Mutex),
}, nil
}
func (p *Pool) Get() IConnection {
if len(p.idle) == 0 {
conn := NewConnection()
_ = p.Put(conn)
}
c := p.idle[0]
p.idle = p.idle[1:]
return c
}
func (p *Pool) Put(conn IConnection) error {
p.idle = append(p.idle, conn)
return nil
}