Tags: #pool #concurrency #go #golang
// http://www.akshaydeo.com/blog/2017/12/23/How-did-I-improve-latency-by-700-percent-using-syncPool/
import (
"fmt"
"sync"
"time"
)
// Pool for our struct A
var pool *sync.Pool
// A dummy struct with a member
type A struct {
Name string
}
// Func to init pool
func initPool() {
pool = &sync.Pool {
New: func()interface{} {
fmt.Println("Returning new A")
return new(A)
},
}
}
// Main func
func main() {
// Initializing pool
initPool()
// Get hold of instance one
one := pool.Get().(*A)
one.Name = "first"
fmt.Printf("one.Name = %s\n", one.Name)
// Submit back the instance after using
pool.Put(one)
// Now the same instance becomes usable by another routine without allocating it again
//
// Note: depending on the data type in your pool, you might want to make sure that you
// zero out the data in the object before putting it back into the pool.
//
// An example of this would be a complex/expensive object creation for user authentication.
// But putting back a user object with a username/password would be bad as the next request
// would pull those values out of the pool.
//
// Meaning, if you use the pool for reducing the overhead of recreating objects, then that's
// fine but just be aware of making the pool dirty by putting back stateful objects.
}