cleancache

package
v0.0.0-...-48d2a37 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2025 License: MIT Imports: 4 Imported by: 0

README

Clean Cache (Timer)

GoDoc Go Report Card

NOTE While you can use the code here, the code is simply for a medium article.

Introduction

This package is similar to the root version, except it can remove a value that was added back between a timeout and a GC cycle. This will not cause any issues, it is just not as efficient. But it also didn't require using a more customized shardedmap.

This version:

  • Uses weak pointers to automatically collect values no longer in use
  • Automatically delete keys for values no longer in use
  • Shrinks the underlying map when values are deleted
  • Uses sharded maps for better concurrency
  • Thread-safe

Use

It is important to remember this values stay in the cache until a value is no longer in use. Once that occurs, it will live in the cache until a garbage collection occurs

This means that the cache is optimized for storage size and constant use.

There is no maximum size, either the values are being used and remain in the cache during collection or they aren't, where caches without weak pointers can't determine if something is in use and rely on TTL and LRU semantics generally.

This cache relies on pointer values. Heavy parallel set and get times will be more expensive than using maps with locks, sync.Map or something like bigcache, but less than the version at the repo root.

The following show the semantics for using the cache:

Create the cache

cache, err := New[int, Data](ctx)
if err != nil {
	panic(err)
}

Set a value in the cache

id := 0
d := &Data{Name: "John"}
oldValue, oldValueExisted := cache.Set(id, d)

Get a value from the cache

value, ok := cache.Get(id)
if !ok {
	return fmt.Errorf("value not in cache")
}

Delete a value form the cache

// Old is the value you deleted, ok is true if the value was deleted vs just not found.
old, ok := cache.Del(id)

Documentation

Overview

Package cleancache provides a thread-safe weak pointer cache that automatically cleans up entries when the weakly referenced objects are garbage collected. It supports basic operations like Get, Set, and Del. It uses a shared map for concurrency that also shrinks with deleted keys. The sharded map is based on Tidwall's shardedmap implementation, but updated for generics and uses the maphash package. The cache has no size limit and relies on Go's runtime to manage memory once objects are no longer referenced. Unlike the base version at cleancache/cache.go, this version does not use a custom hashmap implementation, but instead uses a sharded map from the gostdlib library. These are virtually identical except the other optimizes a few calls at a lower level. This version is simpler.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Cache

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

Cache is a weakPointer cache. It provides a cache of objects that have weak pointers to them. When the weak pointer's value becomes nil, we delete the key. This cache is thread-safe.

func New

func New[K comparable, V any](ctx context.Context, options ...Option) (*Cache[K, V], error)

New creates a new Cache with the given options.

func (*Cache[K, V]) Del

func (c *Cache[K, V]) Del(k K) (prev *V, ok bool)

Del deletes a value for a key. Returns the deleted value, or false when no value was assigned.

func (*Cache[K, V]) Get

func (c *Cache[K, V]) Get(k K) (value *V, ok bool)

Get retrieves a value at Key.

func (*Cache[K, V]) Len

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

Len returns the number of entries in the cache.

func (*Cache[K, V]) Set

func (c *Cache[K, V]) Set(k K, v *V) (Prev *V, ok bool)

Set stores a key with value. If the key already exists, this will overwrite it. In that case we return the previous value and true. If v is nil, we delete the key and return the previous value.

type Option

type Option func(opts) (opts, error)

Option is an option for New().

Jump to

Keyboard shortcuts

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