sync.Once and sync.Map
One-time initialization and concurrent maps
sync.Once and sync.Map is a free Go Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Go Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
sync.Once
sync.Once guarantees that a function runs exactly once, no matter how many goroutines call it concurrently. Classic use case: lazy initialisation of a singleton.
Once.Do
Only the first call to Do executes the function; subsequent calls are no-ops even if called from different goroutines.
var once sync.Once
var db *Database
func getDB() *Database {
once.Do(func() { db = openDB() })
return db
}Once does not reset
Once a sync.Once has fired, it cannot be reset. If you need resettable one-time execution, manage state manually with an atomic or mutex.
Once panic behaviour
If the function passed to Do panics, Do is considered done and future calls are no-ops. The panic propagates to the first caller.
sync.Map overview
sync.Map is a concurrent map with no external locking. It is optimised for two patterns: (1) write-once, read-many; (2) disjoint key sets per goroutine.
sync.Map methods
Key methods: Store, Load, LoadOrStore, Delete, Range. No generic type parameters — keys and values are interface{}.
var m sync.Map
m.Store("key", 42)
v, ok := m.Load("key")
if ok { fmt.Println(v.(int)) }LoadOrStore
LoadOrStore returns the existing value if the key exists, otherwise stores and returns the new value. The boolean indicates whether the value was loaded (true) or stored (false).
actual, loaded := m.LoadOrStore("key", "default")
if loaded { fmt.Println("existing:", actual) }Range
Range iterates all key-value pairs calling the function for each. Return false to stop iteration.
m.Range(func(k, v any) bool {
fmt.Println(k, v)
return true // continue
})When to use sync.Map
Prefer a regular map with a Mutex for most cases — it is simpler and often faster. Use sync.Map when profiling shows contention or the access pattern matches its optimisation targets.
LoadAndDelete
LoadAndDelete atomically loads the value and deletes the key, returning the previous value and whether it was present.
v, loaded := m.LoadAndDelete("key")
if loaded { fmt.Println("deleted:", v) }sync.Map is not generic
Values stored in sync.Map are any. Wrap sync.Map in a typed struct with type-safe methods to avoid scattered type assertions in your codebase.
Quick Check
What does sync.Once guarantee?
Recap: sync.Once and sync.Map
Key points:
- sync.Once: run a function exactly once; irreversible
- sync.Map: concurrent map optimised for read-heavy or disjoint-key patterns
- Use typed wrappers around sync.Map for safety
Frequently asked questions
Is the “sync.Once and sync.Map” lesson free?
Yes — the full text of “sync.Once and sync.Map” is free to read here on the web, and the Go Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Go Academy course, upgrade to CoddyKit PRO.
What will I learn in “sync.Once and sync.Map”?
One-time initialization and concurrent maps You practise Go Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Go Academy?
No prior experience is required. Go Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “sync.Once and sync.Map” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Go Academy lesson?
Yes. Every Go Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- sync.Mutex and sync.RWMutex
- sync.WaitGroup
- sync.Once and sync.Map
- Race Detector and Safe Patterns