navidrome/utils/singleton/singleton.go

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

45 lines
823 B
Go
Raw Normal View History

2021-06-20 02:56:56 +02:00
package singleton
import (
"fmt"
2021-06-20 02:56:56 +02:00
"reflect"
"sync"
2021-06-20 02:56:56 +02:00
"github.com/navidrome/navidrome/log"
)
var (
instances = make(map[string]any)
lock sync.RWMutex
2021-06-20 02:56:56 +02:00
)
// GetInstance returns an existing instance of object. If it is not yet created, calls `constructor`, stores the
// result for future calls and returns it
func GetInstance[T any](constructor func() T) T {
var v T
name := reflect.TypeOf(v).String()
2021-06-20 02:56:56 +02:00
v, available := func() (T, bool) {
lock.RLock()
defer lock.RUnlock()
v, available := instances[name].(T)
return v, available
2021-06-20 02:56:56 +02:00
}()
if available {
return v
}
lock.Lock()
defer lock.Unlock()
v, available = instances[name].(T)
if available {
return v
}
v = constructor()
log.Trace("Created new singleton", "type", name, "instance", fmt.Sprintf("%+v", v))
instances[name] = v
return v
2021-06-20 02:56:56 +02:00
}