9 Destroy func(interface{})
11 created int32 //Number of objects created
15 NewPool creates thread safe Pool object and returns a pointer to it.
16 poolSize int - sets the capacity of the pool
17 newObj func - specifies a function to generate a value (pool element)
18 destroyObj func - specifies a function to destroy a value (pool element)
20 func NewPool(poolSize int, newObj func() interface{}, destroyObj func(interface{})) *Pool{
24 pool: make(chan interface{}, poolSize),
29 Retrieve an object from the pool.
30 If the pool is empty and the number of used object is less than capacity, a new object is created by calling New.
31 Otherwise, the method blocks until an object is returned to the pool.
33 func (p *Pool) Get() interface{} {
38 if atomic.AddInt32(&p.created, 1) <= int32(cap(p.pool)) && p.New != nil {
42 return <-p.pool //block waiting
46 Return an object to the pool.
47 If capacity is exceeded the object is discarded after calling Destroy on it if Destroy is not nil.
49 func (p *Pool) Put(obj interface{}) {
62 Closes the pool and if Destroy is not nil, call Destroy on each object in the pool
63 The pool must not be used once this method is called.
65 func (p *Pool) Close() {
67 available := len(p.pool)
69 for obj := range p.pool {
74 atomic.AddInt32(&p.created, -int32(available))
78 available - the number of available instances
79 created - the number of created instances
81 func (p *Pool) Stats() (available int, created int) {
82 return len(p.pool), int(p.created)