Golang / GoLang Concurrency Mastery Interview Questions
What is the check-then-act race condition (TOCTOU) and how do you fix it?
The Time Of Check, Time Of Use (TOCTOU) race: a goroutine checks a condition, releases the lock, then acts — but between check and act another goroutine changes the condition. The fix is to hold the lock for the entire check-and-act sequence, or use an atomic compare-and-swap.
// BUGGY: check-then-act race — lock released between check and act
type Cache struct {
mu sync.Mutex
items map[string]string
}
func (c *Cache) GetOrComputeBuggy(key string, compute func() string) string {
c.mu.Lock()
val, ok := c.items[key] // CHECK
c.mu.Unlock()
if ok { return val }
// ← Another goroutine may compute and cache here
result := compute() // expensive — no lock held
c.mu.Lock()
c.items[key] = result // ACT — may overwrite another goroutine's result
c.mu.Unlock()
return result
}
// FIX 1: singleflight — one computation per key at a time
import "golang.org/x/sync/singleflight"
var group singleflight.Group
func (c *Cache) GetOrComputeSF(key string, compute func() string) string {
v, _, _ := group.Do(key, func() (any, error) {
c.mu.Lock()
if val, ok := c.items[key]; ok {
c.mu.Unlock()
return val, nil
}
c.mu.Unlock()
result := compute()
c.mu.Lock()
c.items[key] = result
c.mu.Unlock()
return result, nil
})
return v.(string)
}
// FIX 2: sync.Map.LoadOrStore — atomic check-and-store
var sm sync.Map
actual, loaded := sm.LoadOrStore(key, expensiveValue)
// CAUTION: expensiveValue is computed before the call regardless
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...
