Skip to content

Instantly share code, notes, and snippets.

@franklinsales
Created April 3, 2026 22:44
Show Gist options
  • Select an option

  • Save franklinsales/3efe408767cccf66673fde368c25b32c to your computer and use it in GitHub Desktop.

Select an option

Save franklinsales/3efe408767cccf66673fde368c25b32c to your computer and use it in GitHub Desktop.
Golang Singleton using sync.once
package main
//go 1.25 required
import (
"fmt"
"sync"
)
var (
instance *Database
mutex sync.Mutex
)
func GetInstance() *Database {
if instance == nil { // Primeira verificação sem lock para evitar o custo do mutex quando a instância já existe.
mutex.Lock()
defer mutex.Unlock()
if instance == nil { // Segunda verificação dentro do lock para garantir que a instância ainda não foi criada por outra goroutine enquanto esperava pelo lock.
instance = &Database{host: "localhost", port: 5432}
fmt.Println("Nova instância de Database criada.")
}
}
return instance
}
type Database struct {
host string
port int
}
func main() {
var wg sync.WaitGroup
// Criamos várias goroutines para simular acesso concorrente ao singleton.
for range 5 {
wg.Go(func() {
db := GetInstance()
fmt.Printf("Instância de Database: %p\n", db)
})
}
wg.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment