Use sync.Map and Pool appropriately
Use sync.Map and Pool appropriately
sync.Map is a concurrency-safe specialized map. Its zero value is usable. LoadOrStore atomically returns the existing value or installs the proposed value. For most typed application state, a regular map plus a mutex is easier to reason about. sync.Map is optimized for particular patterns such as write-once/read-many keys or largely disjoint key sets.
package main
import ( "fmt" "sync")
func main() { var m sync.Map a, loaded := m.LoadOrStore("id", 12) fmt.Println(a, loaded) b, loaded := m.LoadOrStore("id", 99) fmt.Println(b, loaded) v, ok := m.Load("id") n, typed := v.(int) fmt.Println(n, ok && typed)}Keys and values use any, so check type assertions and use comparable keys. Range is not a consistent snapshot during concurrent updates. Atomic operations on one entry do not make a transaction across several entries. Protect multi-key invariants with an appropriate higher-level lock or another design.
Expected output:
12 false12 true12 trueReuse temporary buffers
package main
import ( "bytes" "fmt" "sync")
func main() { p := sync.Pool{New: func() any { return new(bytes.Buffer) }} b := p.Get().(*bytes.Buffer) b.Reset() b.WriteString("hello") fmt.Println(b.String()) b.Reset() p.Put(b) b = nil c := p.Get().(*bytes.Buffer) c.Reset() fmt.Println(c.Len()) p.Put(c)}Pool may discard cached objects at any time. New supplies a fresh object when Get would otherwise return nil. Reset before reuse; after Put, do not access the object or retained aliases. Do not use Pool for durable data or resources needing guaranteed cleanup. Reset does not erase underlying bytes; do not pool secret-bearing buffers without a reviewed clearing policy. Measure allocations before adopting it.
Expected output:
hello0Try it locally
Store a synthetic label with sync.Map, delete it, then print whether Load finds it (false).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Synchronization 06: Use sync.Map and Pool appropriately
Check the lesson objective before moving on.
Does Range guarantee a consistent snapshot?
May Pool discard an item?