0PricingLogin
Go Academy · Lesson

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

  1. sync.Mutex and sync.RWMutex
  2. sync.WaitGroup
  3. sync.Once and sync.Map
  4. Race Detector and Safe Patterns
← Back to Go Academy