对象池区别与其他的连接池,它只能存放临时的变量,用来缓解GC的处理压力。
用途:
1.sync.Pool是一个可以存或取的临时对象集合
2.sync.Pool可以安全被多个线程同时使用,保证线程安全
注意、注意、注意,sync.Pool中保存的任何项都可能随时不做通知的释放掉,所以不适合用于像socket长连接或数据库连接池。
sync.Pool主要用途是增加临时对象的重用率,减少GC负担。
type Pool struct {
// 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{}
// contains filtered or unexported fields
}
//从 Pool 中获取元素,元素数量 -1,当 Pool 中没有元素时,会调用 New 生成元素,新元素不会放入 Pool 中,若 New 未定义,则返回 nil
func (p *Pool) Get() interface{}
//往 Pool 中添加元素 x
func (p *Pool) Put(x interface{})
type Foo struct {
count int
}
var pool *sync.Pool
func init() {
pool = &sync.Pool{
New: func() interface{} {
return []*Foo{}
},
}
}
func main() {
//放十个对象进入
for i := 0; i < 10; i++ {
req := pool.Get().([]*Foo) //获取池里面的之前数据
dd := &Foo{
count: i,
}
req = append(req, dd) //组装好的数据
pool.Put(req) //放入池中
}
//再放十个对象进入
for i := 10; i < 20; i++ {
req := pool.Get().([]*Foo)
dd := &Foo{
count: i,
}
req = append(req, dd)
pool.Put(req)
}
res := pool.Get().([]*Foo)
for _, v := range res {
fmt.Println("====res:", v.count)
}