Initialize with Once and helpers
Initialize with Once and helpers
Use sync.Once when several callers need the same initialization completed exactly once. Do runs the first supplied function once and concurrent callers wait for it to finish. A zero Once needs no setup. Use one Once per independent initialization.
package main
import ( "fmt" "sync")
func main() { var once sync.Once var wg sync.WaitGroup n := 0 for i := 0; i < 4; i++ { wg.Add(1) go func() { defer wg.Done(); once.Do(func() { n = 42 }) }() } wg.Wait() fmt.Println(n)}All callers return from Do after the initialization finishes normally. Do does not retry after panic; the Once is considered used. Do not call Do recursively on the same Once: it cannot complete until the first call returns. Use ordinary error handling for operations that require retries.
Expected output:
42Cache a returned result
package main
import ( "fmt" "sync")
func main() { calls := 0 get := sync.OnceValues(func() (string, error) { calls++; return "settings", nil }) a, e := get() b, f := get() fmt.Println(a, b, e == nil, f == nil, calls)}Go 1.21 introduced OnceFunc, OnceValue and OnceValues. OnceValues caches both returned values, even a non-nil error. OnceValue caches one value, and OnceFunc wraps a function with no result. Unlike Once.Do, these wrappers repeat the same panic on every call if initialization panics. Cached mutable results still need protection from later concurrent modification.
Expected output:
settings settings true true 1Try it locally
Wrap a function returning 9 with OnceValue; count actual invocations and print the two results and count: 9 9 1.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 04: Initialize with Once and helpers
Check the lesson objective before moving on.
What happens to a returned error from OnceValues?
Why avoid recursive Do on the same Once?