sync.Once and sync.OnceValue
- Version
- 1.27
- Review
- Draft
Summary#
sync.Once.Do runs one function once and waits for it to finish before any call to Do returns. sync.OnceValue wraps a function, computes its result once and returns the cached result to every caller.
Syntax#
var once sync.Once
once.Do(initialize)
load := sync.OnceValue(readSettings)
settings := load()
Example#
package main
import (
"fmt"
"sync"
)
func main() {
load := sync.OnceValue(func() string {
fmt.Println("loading")
return "settings"
})
fmt.Println(load())
fmt.Println(load())
var once sync.Once
for _, caller := range []string{"first", "second"} {
once.Do(func() { fmt.Println("initialized by", caller) })
}
}
Expected output#
loading
settings
settings
initialized by first
Common mistakes#
Use one Once per initialization and avoid copying it after first use. Later Do calls skip their functions, even after an initialization panic. The OnceFunc, OnceValue and OnceValues wrappers repeat the same panic on every call. OnceValues also caches an error returned as a result. Calling Do on the same Once from inside its function deadlocks.
Version applicability#
sync.Once dates back to Go 1.0. The complete example requires Go 1.21, which added OnceFunc, OnceValue and OnceValues. On earlier versions, store the result in a variable that a Once initializes.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0