Per Key Lazy Init With Sync.Once

Give each map key its own sync.Once guarded by one mutex, so expensive per-key setup runs exactly once even when many goroutines race the same key.

GoResilience

Code

gosnippet
53 lines
package main

import (
	"fmt"
	"sync"
)

// entry:每键一个 Once;per-key lazy init,首个调用者计算,其余等待复用
type entry struct {
	once  sync.Once
	value string
}

type lazyTable struct {
	mu      sync.Mutex
	entries map[string]*entry
}

func (t *lazyTable) lookup(key string) string {
	t.mu.Lock()
	e, ok := t.entries[key]
	if !ok {
		e = &entry{}
		t.entries[key] = e
	}
	t.mu.Unlock()

	// 昂贵计算放在锁外:Once 保证每键只算一次,其他 goroutine 原地等结果
	e.once.Do(func() {
		e.value = "computed:" + key
	})
	return e.value
}

func main() {
	table := &lazyTable{entries: make(map[string]*entry)}

	results := make([]string, 4)
	var wg sync.WaitGroup
	for i := 0; i < 4; i++ {
		wg.Add(1)
		go func(i int) {
			defer wg.Done()
			results[i] = table.lookup("config")
		}(i)
	}
	wg.Wait()

	for i, r := range results {
		fmt.Println("call", i, "->", r)
	}
	fmt.Println("other:", table.lookup("other"))
}

How the code behaves

The working parts are the functions lookup and main.

The file repeats itself only inside for i := 0; i < 4; i++. Work is dispatched on a goroutine. Cleanup is attached with defer, so it runs on every exit path of the function.

Points of care

  • Nothing to set up: the platform already ships every API used.

Applying it

The entry-point signature is func (t *lazyTable) lookup(key string) string

The file’s steps show up in the output as call, other:.

The entry point wires lookup together — run it once and the whole demo flows.

Statements that matter

table := &lazyTable{entries: make(map[string]*entry)}
for i, r := range results {
	fmt.Println("call", i, "->", r)
}
go func(i int) {
	defer wg.Done()
	results[i] = table.lookup("config")
}(i)

Interactive Tools for This Topic

FAQ

What does Per Key Lazy Init With Sync.Once print when run?
The script runs standalone; its 2 labeled outputs include `call`, `other:`.