Sobes.tech
Junior — Middle

Can you explain how sync.Map works in Go and how it differs from standard maps?

sobes.tech AI

Answer from AI

sync.Map in Go is a thread-safe map designed for concurrent access without the need to explicitly use mutexes (sync.Mutex). Unlike a regular map[K]V, which is not thread-safe and requires external synchronization, sync.Map implements internal mechanisms for safe reading and writing from multiple goroutines.

Features of sync.Map:

  • Optimized for scenarios with frequent reads and infrequent writes.
  • Uses internal structures and algorithms (e.g., copying during writes) to minimize locking.
  • Provides methods Load, Store, LoadOrStore, Delete, and Range.

Example usage:

var m sync.Map

// Store a value
m.Store("key", "value")

// Load a value
if val, ok := m.Load("key"); ok {
    fmt.Println(val)
}

// Delete a value
m.Delete("key")

// Iterate over elements
m.Range(func(k, v interface{}) bool {
    fmt.Println(k, v)
    return true // continue iteration
})

Thus, sync.Map is convenient when you need to work quickly and safely with a shared map in a multithreaded environment without worrying about mutexes. However, for scenarios with frequent writes and complex logic, it is better to use regular maps with explicit synchronization.