syncutil

package
v0.4.6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 26, 2026 License: MIT Imports: 2 Imported by: 0

Documentation

Overview

Package syncutil provides concurrency utilities.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MapGetOrCreate added in v0.3.33

func MapGetOrCreate[K comparable, V any](
	mu *sync.RWMutex,
	cache map[K]V,
	key K,
	create func() (V, error),
) (V, error)

MapGetOrCreate looks up key in cache under a read lock; if missing, acquires a write lock, double-checks, and calls create to populate the entry. The entry is stored in cache only when create returns a nil error. create is called while the write lock is held, so it is safe for create to read or write other fields protected by the same mu.

Types

type TTLCache added in v0.3.26

type TTLCache[K comparable, V any] struct {
	// contains filtered or unexported fields
}

TTLCache is a thread-safe generic get-or-create cache that combines lazy TTL eviction with an LRU size cap.

On every TTLCache.GetOrCreate call, all entries whose idle time exceeds the configured TTL are evicted first. If the cache is still at capacity after TTL eviction, the least-recently-used entry is evicted to make room.

func NewTTLCache added in v0.3.26

func NewTTLCache[K comparable, V any](ttl time.Duration, maxSize int) *TTLCache[K, V]

NewTTLCache creates a new TTLCache with the given entry TTL and maximum size. Entries idle longer than ttl are evicted lazily; when the cache reaches maxSize the least-recently-used entry is evicted on the next GetOrCreate call.

func (*TTLCache[K, V]) GetOrCreate added in v0.3.26

func (c *TTLCache[K, V]) GetOrCreate(key K, create func() V) V

GetOrCreate returns the cached value for key. If the key is not present, or has been evicted, create is called to produce a new value which is then stored and returned.

On each call, all expired entries are lazily evicted before the lookup. If the cache has reached its capacity after TTL eviction, the LRU entry is removed to make room.

create is called while the cache lock is held.

func (*TTLCache[K, V]) Len added in v0.3.26

func (c *TTLCache[K, V]) Len() int

Len returns the current number of entries held in the cache.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL