Class: Optimizely::LRUCache

Inherits:
Object
  • Object
show all
Defined in:
lib/optimizely/odp/lru_cache.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(capacity, timeout_in_secs) ⇒ LRUCache

Returns a new instance of LRUCache.



25
26
27
28
29
30
31
32
33
# File 'lib/optimizely/odp/lru_cache.rb', line 25

def initialize(capacity, timeout_in_secs)
  # @param capacity - The max size of the cache. If set <= 0, caching is disabled.
  # @param timeout_in_secs - Seconds until a cache item is considered stale.
  #                          If set <= 0, items never expire.
  @cache_mutex = Mutex.new
  @map = {}
  @capacity = capacity
  @timeout = timeout_in_secs
end

Instance Attribute Details

#capacityObject (readonly)

Least Recently Used cache that invalidates entries older than the timeout.



23
24
25
# File 'lib/optimizely/odp/lru_cache.rb', line 23

def capacity
  @capacity
end

#timeoutObject (readonly)

Least Recently Used cache that invalidates entries older than the timeout.



23
24
25
# File 'lib/optimizely/odp/lru_cache.rb', line 23

def timeout
  @timeout
end

Instance Method Details

#lookup(key) ⇒ Object

Retrieve the non stale value from the cache corresponding to the provided key or nil if key is not found Moves the key/value pair to the end of the cache

Parameters:

  • key
    • The key to retrieve



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/optimizely/odp/lru_cache.rb', line 41

def lookup(key)
  return nil if @capacity <= 0

  @cache_mutex.synchronize do
    return nil unless @map.include?(key)

    element = @map.delete(key)
    return nil if element.stale?(@timeout)

    @map[key] = element

    element.value
  end
end

#peek(key) ⇒ Object

Retrieve a value from the cache for a given key or nil if key is not found Doesn’t update the cache

Parameters:

  • key
    • The key to retrieve



89
90
91
92
93
# File 'lib/optimizely/odp/lru_cache.rb', line 89

def peek(key)
  return nil if @capacity <= 0

  @cache_mutex.synchronize { @map[key]&.value }
end

#resetObject

Clears the cache



77
78
79
80
81
82
# File 'lib/optimizely/odp/lru_cache.rb', line 77

def reset
  return if @capacity <= 0

  @cache_mutex.synchronize { @map.clear }
  nil
end

#save(key, value) ⇒ Object

Save a key/value pair into the cache Moves the key/value pair to the end of the cache

Parameters:

  • key
    • A user key

  • value
    • A user value



62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/optimizely/odp/lru_cache.rb', line 62

def save(key, value)
  return if @capacity <= 0

  @cache_mutex.synchronize do
    @map.delete(key) if @map.key?(key)

    @map[key] = CacheElement.new(value)

    @map.delete(@map.first[0]) if @map.size > @capacity
    nil
  end
end