Class: Datadog::Core::Utils::LRUCache
- Inherits:
-
Object
- Object
- Datadog::Core::Utils::LRUCache
- Extended by:
- Forwardable
- Defined in:
- lib/datadog/core/utils/lru_cache.rb
Overview
An LRU (Least Recently Used) cache implementation that relies on the Ruby 1.9+ ‘Hash` implementation that guarantees insertion order.
WARNING: This implementation is NOT thread-safe and should be used
in a single-threaded context or guarded by Mutex.
Instance Method Summary collapse
-
#[](key) ⇒ Object
NOTE: Accessing a key moves it to the end of the list.
- #[]=(key, value) ⇒ Object
-
#initialize(max_size) ⇒ LRUCache
constructor
A new instance of LRUCache.
Constructor Details
#initialize(max_size) ⇒ LRUCache
Returns a new instance of LRUCache.
18 19 20 21 22 23 24 |
# File 'lib/datadog/core/utils/lru_cache.rb', line 18 def initialize(max_size) raise ArgumentError, 'max_size must be an Integer' unless max_size.is_a?(Integer) raise ArgumentError, 'max_size must be greater than 0' if max_size <= 0 @max_size = max_size @store = {} end |
Instance Method Details
#[](key) ⇒ Object
NOTE: Accessing a key moves it to the end of the list.
27 28 29 30 31 |
# File 'lib/datadog/core/utils/lru_cache.rb', line 27 def [](key) if (entry = @store.delete(key)) @store[key] = entry end end |
#[]=(key, value) ⇒ Object
33 34 35 36 37 38 39 40 41 |
# File 'lib/datadog/core/utils/lru_cache.rb', line 33 def []=(key, value) if @store.delete(key) @store[key] = value else # NOTE: evict the oldest entry if store reached the maximum allowed size @store.shift if @store.size >= @max_size @store[key] = value end end |