snippetgoModeratepending
Go sync.Map for concurrent map access
Viewed 0 times
sync.Mapconcurrent mapmutexRWMutexthread safe
Problem
Regular Go maps are not safe for concurrent access. Need a thread-safe map without manual mutex management.
Solution
sync.Map vs mutex-protected map:
When to use sync.Map:
When to use mutex map:
import "sync"
// Option 1: sync.Map (optimized for specific patterns)
var cache sync.Map
// Store
cache.Store("key", "value")
// Load
if val, ok := cache.Load("key"); ok {
fmt.Println(val.(string))
}
// LoadOrStore (get existing or set new)
actual, loaded := cache.LoadOrStore("key", "default")
// loaded=true: key existed, actual=existing value
// loaded=false: key was new, actual="default"
// Delete
cache.Delete("key")
// Range (iterate)
cache.Range(func(key, value any) bool {
fmt.Printf("%v: %v\n", key, value)
return true // return false to stop
})
// Option 2: Generic mutex map (better for most cases)
type SafeMap[K comparable, V any] struct {
mu sync.RWMutex
m map[K]V
}
func NewSafeMap[K comparable, V any]() *SafeMap[K, V] {
return &SafeMap[K, V]{m: make(map[K]V)}
}
func (s *SafeMap[K, V]) Get(key K) (V, bool) {
s.mu.RLock()
defer s.mu.RUnlock()
val, ok := s.m[key]
return val, ok
}
func (s *SafeMap[K, V]) Set(key K, val V) {
s.mu.Lock()
defer s.mu.Unlock()
s.m[key] = val
}When to use sync.Map:
- Keys are stable (mostly reads, rare writes)
- Many goroutines access disjoint key sets
When to use mutex map:
- Everything else (most common case)
- Need type safety (sync.Map uses any)
Why
Concurrent map access in Go causes a runtime panic. sync.Map is optimized for specific access patterns, but a mutex-protected map is simpler and sufficient for most cases.
Gotchas
- Regular map concurrent access causes fatal panic, not data corruption
- sync.Map has no Len() method
- sync.Map uses any type - no generics support
Context
Go programs with concurrent map access from multiple goroutines
Revisions (0)
No revisions yet.