CodeBlanks Logo Icon CodeBlanks

sync.Pool

Learn object reuse with Pool.

sync.Pool

sync.Pool recycles temporary objects to reduce GC pressure. You get an object with Get() and return it with Put(). If the pool is empty New creates one.

Pool is ideal for short-lived reusable objects (e.g. buffers, byte slices). But Pool may be cleared during GC; there is no persistence guarantee. So it is not for state.

Pool and reuse

Pool recycles buffers or temporary slices. var pool = sync.Pool{New: func() interface{} { return &bytes.Buffer{} }} creates a fresh buffer. pool.Get().(*bytes.Buffer) takes, pool.Put(buf) returns.

An object from the pool may not be empty; reset it before use (e.g. buf.Reset()). This prevents stale data from causing issues.

Practice Print with Pool

Inside main, add a sync.Pool declaration and print pool done with fmt.Println.

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "sync"
)

func main() {
    var pool sync.Pool
    pool.New = func() interface{} { return "x" }
    v := pool.Get()
    fmt.Println("pool tamam")
    _ = v
}

Expected output

pool tamam

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does sync.Pool reduce?

  • Network latency
  • Memory leaks
  • CPU usage
  • GC pressure Correct answer

Explanation: Memory leaks are not directly about Pool.

2 Pool usage

Question
var pool = sync.Pool{
    New: func() interface{} { return &Buffer{} },
}
buf := pool.____().(*Buffer)
// use buf
pool.Put(buf)
Answer
var pool = sync.Pool{
    New: func() interface{} { return &Buffer{} },
}
buf := pool.Get().(*Buffer)
// use buf
pool.Put(buf)

Explanation: New is the constructor, Get is the getter.

3 Match Pool concepts

Term Meaning
Get Al
Put Koy
New Create
sync.Pool Tip

All lessons in Intermediate