Junior — Middle
What are the differences between using a regular map with locks and the sync.Map structure for storing data?
sobes.tech AI
Answer from AI
A regular map in Go is not thread-safe, so when accessed concurrently from multiple goroutines, locks (such as sync.Mutex or sync.RWMutex) are needed to protect data. This requires additional code and can lead to blocking and reduced performance under high contention.
sync.Map is a specialized thread-safe data structure optimized for scenarios with frequent read operations and infrequent writes. It implements internal synchronization and optimization mechanisms, allowing to avoid explicit locks in the code.
Main differences:
- Thread safety:
sync.Mapis inherently thread-safe, a regular map is not. - Performance:
sync.Mapis efficient with many parallel reads and rare writes; a regular map with locks may be faster under low contention. - API:
sync.Maphas a limited set of methods (Load,Store,Delete,Range), and does not support direct access via indexing.
Example of using sync.Map:
var m sync.Map
m.Store("key", "value")
if val, ok := m.Load("key"); ok {
fmt.Println(val)
}
If you need a simple map with access control, you can use a map with sync.RWMutex:
var (
mu sync.RWMutex
m = make(map[string]string)
)
// Writing
mu.Lock()
m["key"] = "value"
mu.Unlock()
// Reading
mu.RLock()
val := m["key"]
mu.RUnlock()