Go

sync.Once — Lazy One-Time Initialization

admin by @admin ADMIN
Jun 17, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Run a function exactly once, even from many goroutines. Standard pattern for lazy singletons, expensive setup, and one-time configuration.
Go
Raw
package main

import (
    "fmt"
    "sync"
)

var (
    initOnce sync.Once
    config   map[string]string
)

func loadConfig() {
    initOnce.Do(func() {
        fmt.Println("loading config (this prints exactly once)")
        config = map[string]string{
            "db_url": "postgres://...",
            "port":   "8080",
        }
    })
}

func GetConfig() map[string]string {
    loadConfig()
    return config
}

func main() {
    var wg sync.WaitGroup
    for i := 0; i < 5; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            cfg := GetConfig()
            fmt.Println("port:", cfg["port"])
        }()
    }
    wg.Wait()
    // "loading config" prints ONCE regardless of goroutine count
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.