sync.Once and sync.Map
One-time initialization and concurrent maps
sync.Once
sync.Once guarantees that a function runs exactly once, no matter how many goroutines call it concurrently. Classic use case: lazy initialisation of a singleton.
Once.Do
Only the first call to Do executes the function; subsequent calls are no-ops even if called from different goroutines.
var once sync.Once
var db *Database
func getDB() *Database {
once.Do(func() { db = openDB() })
return db
}All lessons in this course
- sync.Mutex and sync.RWMutex
- sync.WaitGroup
- sync.Once and sync.Map
- Race Detector and Safe Patterns