sync.Map
Use `sync.Map` for the narrow cases it was designed for, not as a default concurrent map replacement.
Canonical guidance
- prefer
mapplus mutex by default - use
sync.Mapfor its intended concurrent access patterns - keep the untyped boundary small
Use when
- read-mostly caches
- keys written once then read many times
- concurrent access patterns with disjoint key sets
Avoid
- reaching for
sync.Mapas the default concurrent map - spreading
anytype assertions everywhere - assuming
sync.Mapis automatically faster
Preferred pattern
var cache sync.Map
cache.Store(key, value)
v, ok := cache.Load(key)
Anti-pattern
- replacing a small, easy-to-lock map with
sync.Mapbecause “concurrent data needs a concurrent container”
Explanation: This anti-pattern is tempting because the API looks purpose-built, but it often makes simple state harder to understand and type-check.
Why
sync.Mapis specialized, not a general replacement for ordinary map ownership
Related pages
Sources
- sync package - Go Team
- The Go Memory Model - Go Team