sync.Map
sync.Map is a map that is safe for concurrent use without an extra mutex. Keys and values are any. It is specialized for a few access patterns; it is not a drop-in faster map.
Detailed Explanation
A built-in map panics or races if two goroutines write at once. The usual fix is sync.Mutex around a map[K]V. sync.Map is a different implementation that allows concurrent Load, Store, LoadOrStore, Delete, and Range without you holding a lock.
When the docs say to use it. Two cases: (1) keys are written once and read many times for the rest of the process (caches of after-init data), (2) disjoint goroutines mostly touch disjoint keys. If every request both reads and writes the same hot keys, a mutex plus an ordinary map is often faster and is always easier to type.
API is any. m.Store("n", 3) and v, ok := m.Load("n"); n := v.(int) is the tax. There is no sync.Map[K]V in the standard library as of Go 1.22. A small generic wrapper in your module is a reasonable extra file if you use sync.Map in more than one place.
LoadOrStore is the atomic "insert if missing." It returns the existing value if the key was present, or stores and returns the new one. Use it to make sure only one goroutine starts an expensive fill. CompareAndSwap and Swap exist for more careful updates.
Range can run concurrently with stores. The callback may see a mix of old and new keys. It does not snapshot a consistent whole map. Do not depend on visiting a key that was stored after Range started, or on missing a key that was deleted mid-walk.
What it costs. sync.Map keeps two maps internally and amortizes lock cost for the read-mostly case. For a small map with mixed read/write, a mutex + map is simpler and can be quicker. Do not switch to sync.Map as a first response to a race; switch when the pattern matches and a profile says the mutex is hot.
Code Examples
package main
import (
"fmt"
"sync"
)
func main() {
var m sync.Map
m.Store("port", 8080)
v, ok := m.Load("port")
fmt.Println(v, ok)
}func cacheGet(m *sync.Map, key string, fill func() int) int {
if v, ok := m.Load(key); ok {
return v.(int)
}
v, loaded := m.LoadOrStore(key, fill())
_ = loaded
return v.(int)
}func printAll(m *sync.Map) {
m.Range(func(k, v any) bool {
fmt.Println(k, v)
return true // continue
})
}Common Gotchas
Values are `any`
a wrong assertion panics. Wrap `Load` if more than one type is stored.
`Range` is not a snapshot
treat it as a concurrent walk, not a freeze.
`LoadOrStore` still runs `fill()` in the example above before the store
if `fill` is expensive and must run once, compute after a failed `Load` and accept that two goroutines may both fill; or use a singleflight pattern.
A zero `sync.Map` is ready
no `make`. Do not copy a `sync.Map` after first use.