Publish immutable state safely
Publish immutable state safely
Publication makes fully initialized data visible through synchronization. An atomic pointer can publish an immutable snapshot, allowing readers to see a coherent version without locking each field. Immutability is a design obligation, not enforced by the pointer type.
package main
import ( "fmt" "sync/atomic")
type Config struct { Version int Region string}
func main() { var current atomic.Pointer[Config] current.Store(&Config{1, "west"}) old := current.Load() current.Store(&Config{2, "east"}) fresh := current.Load() fmt.Println(old.Version, old.Region) fmt.Println(fresh.Version, fresh.Region)}Construct before storing the pointer. A reader loads once and uses that object throughout its operation. The old object remains valid while referenced. Separate loads could observe different versions. Handle a nil initial pointer if readers can arrive before initialization.
Expected output:
1 west2 eastCopy mutable input before publishing
package main
import ( "fmt" "sync/atomic")
type Snapshot struct{ Values []int }
func main() { input := []int{2, 4} var p atomic.Pointer[Snapshot] p.Store(&Snapshot{Values: append([]int(nil), input...)}) input[0] = 99 out := make(chan int) go func() { s := p.Load(); out <- s.Values[0] + s.Values[1] }() fmt.Println(<-out)}The snapshot owns separate integer storage. Slices, maps and pointers can share nested objects; copying only the top-level struct is insufficient. Neither readers nor publishers may mutate published reachable state. Concurrent writers deriving updates from old state need a mutex or a suitable compare-and-swap retry protocol to avoid lost updates.
Expected output:
6Try it locally
Publish two immutable Price objects holding 10 and 12; keep the first loaded pointer and print both amounts after replacement.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Memory model 07: Publish immutable state safely
Check the lesson objective before moving on.
What should a reader do to use one coherent snapshot?
Does atomic.Pointer protect mutations of the pointed-to slice?