CodeNebula
Go⚡Concurrencyintermediate

sync.Pool

Go · Concurrency · Run with go run

Explanation

`sync.Pool` is a cache of temporary objects that can be reused to relieve pressure on the garbage collector. `Get` returns an object (creating one via the `New` func if the pool is empty); `Put` returns it for reuse. The pool may drop its contents at any time — never store anything that must persist.

Real-World Scenario

A high-throughput JSON API allocates a `bytes.Buffer` per request to build the response. Under load that's thousands of short-lived allocations per second. A `sync.Pool` of buffers recycles them across requests, cutting GC pauses and allocation cost dramatically.

Quick Snippet

snippet.go
import (
    "bytes"
    "sync"
)

var bufPool = sync.Pool{
    New: func() any { return new(bytes.Buffer) },
}

func handle() {
    buf := bufPool.Get().(*bytes.Buffer)
    buf.Reset()              // always reset reused objects
    defer bufPool.Put(buf)   // return it for the next caller

    buf.WriteString("response body")
    // ... use buf ...
}

Full Example

pool.go
// Compile: go run pool.go
// Output:
//   built: [item-0 item-1 item-2]
//   built: [item-0 item-1 item-2]
//   buffers are reused from the pool
package main

import (
	"bytes"
	"fmt"
	"sync"
)

var bufPool = sync.Pool{
	New: func() any { return new(bytes.Buffer) },
}

func build() string {
	buf := bufPool.Get().(*bytes.Buffer)
	buf.Reset()            // always reset a reused object
	defer bufPool.Put(buf) // return it for the next caller

	for i := 0; i < 3; i++ {
		if i > 0 {
			buf.WriteString(" ")
		}
		fmt.Fprintf(buf, "item-%d", i)
	}
	return buf.String()
}

func main() {
	fmt.Println("built: [" + build() + "]")
	fmt.Println("built: [" + build() + "]")
	fmt.Println("buffers are reused from the pool")
}
Run command
go run pool.go