sync.Once and Choosing Between a Mutex and a Channel
sync.Once
Sometimes a piece of work has to run exactly once, even if many goroutines trigger it, like reading a config file or opening a database connection the first time it's needed (lazy initialization).
sync.Once handles this:
var (
once sync.Once
kamus map[string]string
)
func Terjemahkan(kata string) string {
once.Do(func() {
// hanya dijalankan pada pemanggilan Do yang pertama
kamus = map[string]string{"halo": "hello", "terima kasih": "thank you"}
})
return kamus[kata]
}
What once.Do(f) guarantees:
fruns at most once, no matter how many goroutines callDo.- Other goroutines that call
Dowhilefis still running wait untilffinishes, so every caller sees fully initialized data.
Go 1.21 also added
sync.OnceValueandsync.OnceFunc, shorter versions for similar cases.
Mutex or channel?
The previous chapter taught a Go proverb: don't communicate by sharing memory; share memory by communicating. So why are we now locking shared memory?
They're different tools for different problems. An easy way to remember it:
Channels orchestrate; mutexes serialize.
- Channels are good for moving data and coordinating work: pipelines, worker pools, signaling "done", passing results from one goroutine to another. Ownership of the data moves along with the message.
- Mutexes are good for guarding shared state that many goroutines access: counters, caches, stats maps, balances. The data stays where it is; access to it takes turns (it's serialized).
Pick whichever makes the code simplest and easiest to read. If you find yourself spinning up a goroutine and a channel just to protect a single counter variable, a mutex is usually clearer. On the other hand, if you're stacking up mutexes to control the order of work between goroutines, a channel is probably a better fit.
Task
A chat app loads user settings (theme, language, time zone) lazily. The muat() method and the Pengaturan struct are already provided; muat() records how many times it has been called in the jumlahMuat field.
Change the func (p *Pengaturan) Ambil(kunci string) string method so it calls muat() through p.once.Do, so the settings are loaded only once, even when Ambil is called many times from many goroutines. Ambil should still return the value for kunci (or an empty string if there isn't one).