Go Sync Pool
A sync pool is a shared store that holds values for quick reuse. A program takes a value out, uses it, and puts it back for the next use.
An empty pool builds a value
The pool starts empty, so the first Get calls New. Put stores a string, and the next Get returns that string.
package main
import (
"fmt"
"sync"
)
func main() {
pool := sync.Pool{
New: func() any {
return "fresh"
},
}
fmt.Println(pool.Get())
pool.Put("stored")
fmt.Println(pool.Get())
}A pool of text buffers
The pool holds buffers that write text. The second line shows the empty text left after the reset.
package main
import (
"bytes"
"fmt"
"sync"
)
func main() {
pool := sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
b := pool.Get().(*bytes.Buffer)
b.WriteString("report ready")
fmt.Println(b.String())
b.Reset()
pool.Put(b)
next := pool.Get().(*bytes.Buffer)
fmt.Printf("%q\n", next.String())
}The same buffer serves twice
The loop builds a report, prints it, and puts the buffer back. The second pass prints the same text from the reused buffer.
package main
import (
"bytes"
"fmt"
"sync"
)
func main() {
pool := sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
for i := 0; i < 2; i++ {
b := pool.Get().(*bytes.Buffer)
b.WriteString("Weekly report")
fmt.Println(b.String())
b.Reset()
pool.Put(b)
}
}Example
package main
import (
"bytes"
"fmt"
"sync"
)
func main() {
pool := sync.Pool{
New: func() any {
return new(bytes.Buffer)
},
}
labels := []string{"pen", "cup", "box"}
for _, name := range labels {
b := pool.Get().(*bytes.Buffer)
b.WriteString("Label: ")
b.WriteString(name)
fmt.Println(b.String())
b.Reset()
pool.Put(b)
}
}Key points
- A sync pool keeps ready values so a program can reuse them instead of building new ones.
- The New field names a function that builds a value when the pool is empty.
- Get takes a value out of the pool.
- Put places a value back in the pool for a later Get.
- A buffer is reset before Put so the next Get starts with a clean value.
- The pool may drop any stored value at a garbage collection.
- Never keep the only copy of anything in a pool.
In this example, one pool holds a single text buffer. The loop takes the buffer out for each label in turn. Each pass writes the word Label and one name, then prints the line. The buffer is reset and put back after each label, so all three labels share the same buffer.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
What does Get return when a sync pool is empty?