sync.Once, sync.Pool and sync.Map

Three types in sync solve three narrow problems: something that must happen exactly once, objects that are expensive to allocate and cheap to reuse, and a map that several goroutines write at the same time. Each has a condition that makes it the wrong choice, and the condition is the more useful half of the lesson.

sync.Once

once.Do(f) runs f on the first call and does nothing on every later one, from whichever goroutine. Callers that arrive while f runs wait for it to finish, so a slow initialiser does not let a second one start. The three workers below all call Do and the initialiser printed once.

package main import ( "fmt" "sync" ) func main() { var once sync.Once var wg sync.WaitGroup for i := 0; i < 3; i++ { wg.Add(1) go func() { defer wg.Done() once.Do(func() { fmt.Println("initialised once") }) fmt.Println("worker done") }() } wg.Wait() }

go build -o app main.go && ./app

initialised once
worker done
worker done
worker done

The initialiser line comes first because every worker that lost the race was blocked inside Do until it finished. A panic inside f counts as the one call and propagates to the caller, so a later call does not retry: an initialiser that can fail should cache the error itself, as the next section does.

sync.OnceValues

sync.OnceValues wraps a function that returns a value and an error and returns a function that computes both once and then always returns the same pair. The count below proves it: the loader ran for the first call and not for the second, and the error came back with the value both times.

package main import ( "errors" "fmt" "sync" ) func main() { calls := 0 load := sync.OnceValues(func() (string, error) { calls++ return "config", errors.New("warning") }) for i := 0; i < 2; i++ { v, err := load() fmt.Println(v, err) } fmt.Println("calls:", calls) }

go build -o app main.go && ./app

config warning
config warning
calls: 1

sync.OnceFunc is the same for a function with no results. Both were added in Go 1.21 and both are the right shape for a configuration load or a schema parse at start-up; both also cache a failure, which is right for a broken config and wrong for a network call that might recover.

sync.Pool

A pool recycles temporary objects between requests. Get returns an item from the pool or calls New when the pool is empty, and Put offers one back. Nothing is guaranteed: the garbage collector may drop the pool's contents between collections, so a pooled buffer must be reset before use and must never carry state a caller expects to find.

package main import ( "fmt" "sync" ) func main() { pool := sync.Pool{ New: func() any { return make([]byte, 0, 8) }, } buf := pool.Get().([]byte) buf = append(buf, "hello"...) fmt.Println("first:", string(buf), len(buf), cap(buf)) buf = buf[:0] pool.Put(buf) buf = pool.Get().([]byte) fmt.Println("second:", len(buf), cap(buf)) }

go build -o app main.go && ./app

first: hello 5 8
second: 0 8

The second buffer came back with length zero and capacity eight because the program reset it before Put. A pool that stores a buffer without resetting it hands the next caller somebody else's data, which is a bug the type system cannot catch: Get returns any and the assertion is the caller's.

sync.Map

A plain map is not safe for concurrent writes, and a sync.Map is: Store, Load, Delete and Range are each atomic. The type is specialised for two patterns, a key written once and read many times, or disjoint keys written by different goroutines. For a map with a mix of reads, writes and deletes, a sync.RWMutex around a plain map is usually faster and always easier to extend.

package main import ( "fmt" "sync" ) func main() { var m sync.Map var wg sync.WaitGroup for i := 1; i <= 3; i++ { wg.Add(1) go func() { defer wg.Done() m.Store(i, i*i) }() } wg.Wait() m.Range(func(k, v any) bool { fmt.Println(k, "->", v) return true }) }

go build -o app main.go && ./app

2 -> 4
3 -> 9
1 -> 1

A second run printed the pairs in the order 1, 2, 3. Range visits the entries in no particular order and the order can change between calls, so a program that needs sorted output collects the keys and sorts them after the Range. A zero sync.Map is ready to use and must not be copied after first use.

Exercises

  1. Put a time.Sleep inside the once initialiser and print a timestamp from every worker. Which workers wait, and what does the timestamp order show?
  2. Remove the buf = buf[:0] before Put and print the second buffer as a string. What data leaks, and which rule of a pool does that break?
  3. Replace the sync.Map with a plain map and a RWMutex and run both under -race. What changes in the report, and which version would you keep for a cache?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. How many times does sync.Once run its function?

    Answer

    Once, across all goroutines

    Callers during the run wait for it to finish.

  2. What is the danger of a panic inside Once.Do?

    Answer

    The once is consumed and a later call does not retry

    An initialiser that can fail should cache the error itself.

  3. What does sync.OnceValues return?

    Answer

    A function that computes a value and an error once and returns the same pair after

    Both results are cached, including the error.

  4. Why does a pooled buffer have to be reset before Put?

    Answer

    Because the next Get would receive the previous data

    A pool has no idea what the buffer was used for.

  5. What may happen to the contents of a sync.Pool?

    Answer

    The garbage collector may drop them

    A pool is a cache, not a guarantee.

  6. What does a sync.Pool New function do?

    Answer

    Creates an item when the pool is empty

    It is the fallback for a miss.

  7. Which map is safe for concurrent writes?

    Answer

    A map with a mutex or a sync.Map

    A plain map races and the runtime can abort the program.

  8. In which order does sync.Map.Range visit entries?

    Answer

    No particular order

    Collect and sort the keys when order matters.

  9. For which pattern is sync.Map the better choice?

    Answer

    A cache with many reads and rare writes

    It is specialised for read-mostly and disjoint-key writes.

  10. When is a plain map with RWMutex usually better?

    Answer

    When reads, writes and deletes are mixed

    It is faster for mixed access and easier to extend.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev