Documentation
¶
Overview ¶
Package lazy provides a generic thread-safe lazy initializer.
Lazy[T] ensures that an expensive initialization function runs exactly once, even under concurrent access. It uses atomic.Pointer for lock-free reads after successful initialization and singleflight.Group to deduplicate concurrent initialization attempts.
If initialization fails, the next Get call retries. There is no caching of failed attempts — every failure triggers a retry on the next access.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Lazy ¶
type Lazy[T any] struct { // contains filtered or unexported fields }
Lazy is a thread-safe lazy initializer for type T. The zero value is not usable; use New to create instances.
func New ¶
New creates a Lazy that will call init on first Get. The init function should return a fully initialized T or an error. If init returns an error, it will be retried on the next Get call.
func (*Lazy[T]) Get ¶
Get returns the initialized value, calling init on first access. Concurrent callers are deduplicated via singleflight — only one init runs at a time; others wait for the result.
When callers are deduplicated, only the first caller's context is passed to init. Use a context with sufficient lifetime (for example, a background or startup context rather than a per-request context).