Sobes.tech
Middle

What do you know about the sync.Map package?

sobes.tech AI

Answer from AI

The sync.Map package provides a concurrency-safe hash table. It is optimized for use cases where keys are mostly read and less frequently written.

Key features:

  • Concurrency safety: Ensures safe access from multiple goroutines without explicit locks.
  • Optimized for reading: The first read of each key caches a read-only copy. Subsequent reads from this cache do not require locking.
  • Dynamic deletion: Removed elements are first marked as deleted, and actual removal occurs under certain conditions to minimize locking during writes.
  • Lack of Len() method: Supporting a Len() method would make the concurrency-safe implementation complex and costly.
  • Not suitable for constantly changing data: With frequent writes and deletions, it may be less efficient than using a mutex with a regular map.

Main methods:

  • Load(key any) (value any, ok bool): Loads the value associated with the key. Returns false if the key is absent.
  • Store(key, value any): Stores a value for the key. Can be used for adding or updating.
  • LoadOrStore(key any, value any) (actual any, loaded bool): Loads the value associated with the key if it exists. Otherwise, stores the provided value. Returns the actual value and a flag indicating whether the value was loaded (true) or stored (false).
  • Delete(key any): Deletes the value for the key.
  • Range(f func(key, value any) bool): Iterates over the map elements in arbitrary order. The function f is called for each key-value pair. If f returns false, iteration stops.

Example usage:

import "sync"

var m sync.Map

func process(key string, value int) {
	m.Store(key, value)

	v, ok := m.Load(key)
	if ok {
		// Use v
	}

	m.Range(func(key, value any) bool {
		// Process elements
		return true // Continue iteration
	})
}

Overall, sync.Map is a good choice when parallel reads significantly outnumber writes and deletions. Otherwise, using a map with sync.Mutex or sync.RWMutex might be more appropriate.