package obj_pool
import (
"errors"
"time"
)
type ResuableObj struct {
}
type ObjPool struct {
bufChan chan *ResuableObj //用于缓冲可重用对象
}
//创建对象
func NewObjPool(numOfObj int) *ObjPool {
objPool := ObjPool{}
objPool.bufChan = make(chan *ResuableObj, numOfObj)
for i := 0; i < numOfObj; i++ {
objPool.bufChan <- &ResuableObj{}
}
return &objPool
}
//获取对象
func (p *ObjPool) GetObj(timeout time.Duration) (*ResuableObj, error) {
select {
//获取对象
case ret := <-p.bufChan:
return ret, nil
// 超时
case <-time.After(timeout):
return nil, errors.New("time out")
}
}
//添加对象
func (p *ObjPool) ReleaseObj(obj *ResuableObj) error {
select {
case p.bufChan <- obj:
return nil
default:
return errors.New("overflow")
}
}