Skip to content

Commit

Permalink
shared: Add SetHealthCheck to interface
Browse files Browse the repository at this point in the history
  • Loading branch information
nekohasekai committed Nov 9, 2024
1 parent 11ffb96 commit 72ff654
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
2 changes: 2 additions & 0 deletions contrab/freelru/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ type Cache[K comparable, V any] interface {
// Lifetime 0 means "forever".
SetLifetime(lifetime time.Duration)

SetHealthCheck(healthCheck HealthCheckCallback[K, V])

// SetOnEvict sets the OnEvict callback function.
// The onEvict function is called for each evicted lru entry.
SetOnEvict(onEvict OnEvictCallback[K, V])
Expand Down
17 changes: 14 additions & 3 deletions contrab/freelru/sharedlru.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,14 @@ func (lru *ShardedLRU[K, V]) SetOnEvict(onEvict OnEvictCallback[K, V]) {
}
}

func (lru *ShardedLRU[K, V]) SetHealthCheck(healthCheck HealthCheckCallback[K, V]) {
for shard := range lru.lrus {
lru.mus[shard].Lock()
lru.lrus[shard].SetHealthCheck(healthCheck)
lru.mus[shard].Unlock()
}
}

func nextPowerOfTwo(val uint32) uint32 {
if bits.OnesCount32(val) != 1 {
return 1 << bits.Len32(val)
Expand All @@ -51,15 +59,17 @@ func nextPowerOfTwo(val uint32) uint32 {

// NewSharded creates a new thread-safe sharded LRU hashmap with the given capacity.
func NewSharded[K comparable, V any](capacity uint32, hash HashKeyCallback[K]) (*ShardedLRU[K, V],
error) {
error,
) {
size := uint32(float64(capacity) * 1.25) // 25% extra space for fewer collisions

return NewShardedWithSize[K, V](uint32(runtime.GOMAXPROCS(0)*16), capacity, size, hash)
}

func NewShardedWithSize[K comparable, V any](shards, capacity, size uint32,
hash HashKeyCallback[K]) (
*ShardedLRU[K, V], error) {
*ShardedLRU[K, V], error,
) {
if capacity == 0 {
return nil, errors.New("capacity must be positive")
}
Expand Down Expand Up @@ -126,7 +136,8 @@ func (lru *ShardedLRU[K, V]) Len() (length int) {
// AddWithLifetime adds a key:value to the cache with a lifetime.
// Returns true, true if key was updated and eviction occurred.
func (lru *ShardedLRU[K, V]) AddWithLifetime(key K, value V,
lifetime time.Duration) (evicted bool) {
lifetime time.Duration,
) (evicted bool) {
hash := lru.hash(key)
shard := (hash >> 16) & lru.mask

Expand Down

0 comments on commit 72ff654

Please sign in to comment.