Sync Once Lazy Singleton Init

Initialize expensive resources exactly once with sync.Once, keeping first-call latency on the caller and all later calls lock-free after the gate.

GoResilience

Code

gosnippet
49 lines
package main

import (
	"fmt"
	"sync"
	"time"
)

type Registry struct {
	services map[string]string
}

var (
	registry *Registry
	initOnce sync.Once
	initErr  error
)

func getRegistry() (*Registry, error) {
	// Do 保证 fn 全程只被一个 goroutine 执行一次;
	// 其余调用者阻塞到 fn 返回后再继续(哪怕 fn 失败也不会重试)
	initOnce.Do(func() {
		fmt.Println("initializing registry (should print once)")
		time.Sleep(50 * time.Millisecond) // 模拟昂贵初始化
		if time.Now().Unix() < 0 {
			initErr = fmt.Errorf("impossible")
		}
		registry = &Registry{services: map[string]string{
			"users": "users.internal:8080",
			"orders": "orders.internal:8080",
		}}
	})
	return registry, initErr
}

func main() {
	var wg sync.WaitGroup
	for i := 0; i < 10; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if reg, err := getRegistry(); err == nil {
				_ = reg.services["users"]
			}
		}()
	}
	wg.Wait()
	fmt.Println("done")
}

The program from its entry point

Sync Once Lazy Singleton Init comes down to the functions getRegistry and main.

The loop for i := 0; i < 10; i++ is the only repeated construct. Work is dispatched on a goroutine. defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Putting it to use

The one signature that matters here is func getRegistry() (*Registry, error)

The demo output is labeled (initializing registry (should print once), done), so each line traces straight back to the statement that printed it.

The demo flow inside main is getRegistry — run the file to see it end to end.

Core lines

initErr = fmt.Errorf("impossible")
var wg sync.WaitGroup
initOnce sync.Once

Interactive Tools for This Topic

FAQ

What does Sync Once Lazy Singleton Init print when run?
Execute the whole file; each printed line is prefixed with a label like `initializing registry (should print once)`, `done`.