What is sync.Pool in golang and How to use it
sync.Pool (1/2)
Many Go libraries include custom thread-safe free lists, like this:
var objPool = make(chan *Object, 10)
func obj() *Object {
select {
case p := <-objPool:
return p
default:
}
return NewObject()
}
func objPut(p *Object) {
select {
case objPool <- p:
default:
}
}
p := obj()
// use p
objPut(p)
- sync.Pool (2/2)
The sync.Pool
type provides a general thread-safe global free list.
It allows the runtime to reclaim entries when appropriate (for example, during garbage collection).
var objPool = sync.Pool{
New: func() interface{} {
return NewObject()
},
}
p := objPool.Get().(*Object)
// use p
objPool.Put(p)