Go course

Mutexessync.Once and Choosing Between a Mutex and a Channel

Go

Display

Theme

Mutexes · Test exercise

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:

  • f runs at most once, no matter how many goroutines call Do.
  • Other goroutines that call Do while f is still running wait until f finishes, so every caller sees fully initialized data.

Go 1.21 also added sync.OnceValue and sync.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).

main.go
package main

import (
	"fmt"
	"sync"
)

type Pengaturan struct {
	once       sync.Once
	data       map[string]string
	jumlahMuat int
}

// muat mensimulasikan pembacaan pengaturan dari server (mahal).
func (p *Pengaturan) muat() {
	p.jumlahMuat++
	p.data = map[string]string{
		"tema":   "gelap",
		"bahasa": "id",
		"zona":   "Asia/Jakarta",
	}
}

func (p *Pengaturan) Ambil(kunci string) string {
	// TODO: panggil muat() melalui p.once.Do agar hanya sekali
	p.muat()
	return p.data[kunci]
}

func main() {
	p := &Pengaturan{}
	fmt.Println("Tema:", p.Ambil("tema"))
	fmt.Println("Bahasa:", p.Ambil("bahasa"))
	fmt.Println("Dimuat sebanyak:", p.jumlahMuat, "kali")
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)