Thread-safe, generic lazy initialization in Go for efficiently managing expensive resources concurrently.
Often, you have resources or values that are expensive to create (e.g., database connections, loaded configuration files, complex computed objects) and you only want to incur that cost when the value is actually needed for the first time. lazyinit
handles the synchronization logic required to make this process safe and efficient in concurrent Go programs.
- Thread-Safe: Uses mutexes and atomic operations to safely handle concurrent calls to
Get()
andReset()
. - Lazy Initialization: The initialization logic runs only when
Get()
is called for the first time (or after aReset()
). - Generics: Fully utilizes Go 1.18+ generics (
[T any]
) for type safety without needinginterface{}
. - Flexible Initialization: Supports initialization with:
- An already computed value (
New
). - A zero-argument function (
NewFromFunc
). - A function accepting arguments (
NewFromFuncWithArgs
).
- An already computed value (
- Resettable: Allows clearing the cached value to force re-initialization on the next
Get()
call. - Initialization Check: Provides
IsInitialized()
to check the status without triggering initialization. - Zero External Dependencies: Uses only the Go standard library.
Use go get -u
command:
go get -u github.com/colduction/lazyinit-go