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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
