TTL Cache
Source: Custom
Topics: sync.RWMutex, time.AfterFunc, Generics, Comparable
Problem
Implement a thread-safe in-memory cache where entries expire automatically after a TTL.
Requirements:
New[K comparable, V any](ttl time.Duration) *Cache[K, V] — create a cache with the given TTL.
Set(key K, val V) — store a value; if the key already exists, update the value and reset the TTL.
Get(key K) (V, bool) — return the value and true, or zero value and false if the key is missing or expired.
Delete(key K) — remove an entry immediately, cancelling its timer.
- Entries expire after TTL without a background polling loop — use
time.AfterFunc.
Type:
type Cache[K comparable, V any] struct { ... }
func New[K comparable, V any](ttl time.Duration) *Cache[K, V]
func (c *Cache[K, V]) Set(key K, val V)
func (c *Cache[K, V]) Get(key K) (V, bool)
func (c *Cache[K, V]) Delete(key K)
Key concepts
- sync.RWMutex:
RLock for Get, Lock for Set/Delete.
- time.AfterFunc: fires the expiry callback in a new goroutine after the TTL; returns a
*time.Timer.
- Timer reset on update: call
timer.Stop() then timer.Reset(ttl) when a key is overwritten.
- Version counter:
Stop() returning false means the timer already fired. A version stamp on each entry lets the AfterFunc callback check it is still relevant before deleting.
Run
go test -v -race -bench=. ./challenges/concurrency/timeout-cache/
Sign in to submit your solution.