github.com/grailbio/base@v0.0.11/ttlcache/ttlcache.go (about)

     1  // Copyright 2018 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache-2.0
     3  // license that can be found in the LICENSE file.
     4  //
     5  // Package ttlcache implements a cache with a fixed TTL. The keys and values
     6  // are interface{} and the TTL for an item starts decreasing each time the item
     7  // is added to the cache.
     8  //
     9  // There is no active garbage collection but expired items are deleted
    10  // from the cache upon new 'Get' calls. This is a lazy strategy that
    11  // does not prevent memory leaks.
    12  
    13  package ttlcache
    14  
    15  import (
    16  	"sync"
    17  	"time"
    18  )
    19  
    20  type cacheValue struct {
    21  	value      interface{}
    22  	expiration time.Time
    23  }
    24  
    25  type Cache struct {
    26  	cache map[interface{}]cacheValue
    27  	mu    sync.Mutex
    28  	ttl   time.Duration
    29  }
    30  
    31  func New(ttl time.Duration) *Cache {
    32  	return &Cache{
    33  		cache: map[interface{}]cacheValue{},
    34  		ttl:   ttl,
    35  	}
    36  }
    37  
    38  func (c *Cache) Get(key interface{}) (interface{}, bool) {
    39  	c.mu.Lock()
    40  	v, ok := c.cache[key]
    41  
    42  	if ok && v.expiration.After(time.Now()) {
    43  		c.mu.Unlock()
    44  		return v.value, true
    45  	}
    46  	if ok {
    47  		delete(c.cache, key) // key is expired - delete it.
    48  	}
    49  	c.mu.Unlock()
    50  	return nil, false
    51  }
    52  
    53  func (c *Cache) Set(key interface{}, value interface{}) {
    54  	c.mu.Lock()
    55  	c.cache[key] = cacheValue{
    56  		value:      value,
    57  		expiration: time.Now().Add(c.ttl),
    58  	}
    59  	c.mu.Unlock()
    60  }