Sure! Here's an implementation of an LRU cache in Go using time-based eviction and generics:
package main
import (
"container/list"
"time"
"sync"
)
type CacheEntry[K any, V any] struct {
key K
value V
expires time.Time
}
type LRUCache[K any, V any] struct {
capacity int
cache map[K]*list.Element
lruList *list.List
mutex sync.Mutex
}
func NewLRUCache[K any, V any](capacity int) *LRUCache[K, V] {
return &LRUCache[K, V{
capacity: capacity,
cache: make(map[K]*list.Element),
lruList: list.New(),
}
}
func (c *LRUCache[K, V]) Get(key K) (V, bool) {
c.mutex.Lock()
defer c.mutex.Unlock()
if elem, ok := c.cache[key]; ok {
entry := elem.Value.(*CacheEntry[K, V])
if entry.expires.Before(time.Now()) {
c.lruList.Remove(elem)
delete(c.cache, key)
return nil, false
}
c.lruList.MoveToFront(elem)
return entry.value, true
}
return nil, false
}
func (c *LRUCache[K, V]) Put(key K, value V, ttl time.Duration) {
c.mutex.Lock()
defer c.mutex.Unlock()
if elem, ok := c.cache[key]; ok {
c.lruList.MoveToFront(elem)
entry := elem.Value.(*CacheEntry[K, V])
entry.value = value
entry.expires = time.Now().Add(ttl)
} else {
entry := &CacheEntry[K, V]{
key: key,
value: value,
expires: time.Now().Add(ttl),
}
elem := c.lruList.PushFront(entry)
c.cache[key] = elem
if c.lruList.Len() > c.capacity {
oldest := c.lruList.Back()
if oldest != nil {
entry := oldest.Value.(*CacheEntry[K, V])
delete(c.cache, entry.key)
c.lruList.Remove(oldest)
}
}
}
}
func main() {
// Example usage
cache := NewLRUCache[string, int](2)
cache.Put("key1", 1, time.Second*10)
cache.Put("key2", 2, time.Second*10)
value, ok := cache.Get("key1")
if ok {
println("Value:", value) // Output: Value: 1
}
cache.Put("key3", 3, time.Second*10)
value, ok = cache.Get("key2")
if !ok {
println("Key not found") // Output: Key not found
}
}
In this implementation, the LRUCache struct holds the capacity of the cache, a map for quick lookups, and a linked list to keep track of the least recently used items. The CacheEntry struct represents each entry in the cache, containing the key, value, and expiration time.
The Get method retrieves a value from the cache based on the given key. If the entry exists and has not expired, it moves the entry to the front of the list to mark it as the most recently used. If the entry has expired, it removes it from the cache and returns false.
The Put method adds or updates an entry in the cache. If the key already exists, it updates the value and expiration time. If the key is new, it creates a new entry and inserts it at the front of the list. If the cache exceeds its capacity, it removes the least recently used entry from the list and the map.
Finally, the main function demonstrates the usage of the LRU cache. Two key-value pairs are added to the cache, and then one of them is retrieved. After adding a third key-value pair, the cache capacity is exceeded, and the second key-value pair is no longer available.