Golang / GoLang Concurrency Mastery Interview Questions
What is sync.Once and what guarantees does it provide?
sync.Once guarantees that a function is executed exactly once, regardless of how many goroutines concurrently call Do(). It is the idiomatic Go approach for thread-safe lazy initialisation and singletons.
// Thread-safe singleton with sync.Once var ( instance *Database once sync.Once ) func GetDB() *Database { once.Do(func() { // Executes exactly once â all other goroutines block until complete instance = &Database{pool: openConnectionPool(config)} }) return instance // always non-nil after once.Do returns } // GUARANTEE: even 1000 concurrent calls to GetDB() // result in exactly one DB initialisation // SUBTLE TRAP: if the function passed to Do panics, // sync.Once considers it 'done' â future calls are no-ops var o sync.Once o.Do(func() { panic("init failed") }) // panics o.Do(func() { /* NEVER RUNS */ }) // silently skipped // Error-aware pattern type result struct{ db *Database; err error } var res result var initOnce sync.Once func getDB() (*Database, error) { initOnce.Do(func() { res.db, res.err = openDB() }) return res.db, res.err } // Go 1.21+: sync.OnceValue / sync.OnceValues (ergonomic wrappers) getConfig := sync.OnceValue(func() *Config { return loadConfig() }) cfg := getConfig() // computed once, cached forever
More Related questions...