Class: LaunchDarkly::ExpiringCache

Inherits:
Object
  • Object
show all
Defined in:
lib/ldclient-rb/expiring_cache.rb

Overview

A thread-safe cache with maximum number of entries and TTL. Adapted from github.com/SamSaffron/lru_redux/blob/master/lib/lru_redux/ttl/cache.rb under MIT license with the following changes:

* made thread-safe
* removed many unused methods
* reading a key does not reset its expiration time, only writing

Instance Method Summary collapse

Constructor Details

#initialize(max_size, ttl) ⇒ ExpiringCache

Returns a new instance of ExpiringCache.



11
12
13
14
15
16
17
# File 'lib/ldclient-rb/expiring_cache.rb', line 11

def initialize(max_size, ttl)
  @max_size = max_size
  @ttl = ttl
  @data_lru = {}
  @data_ttl = {}
  @lock = Mutex.new
end

Instance Method Details

#[](key) ⇒ Object



19
20
21
22
23
24
# File 'lib/ldclient-rb/expiring_cache.rb', line 19

def [](key)
  @lock.synchronize do
    ttl_evict
    @data_lru[key]
  end
end

#[]=(key, val) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/ldclient-rb/expiring_cache.rb', line 26

def []=(key, val)
  @lock.synchronize do
    ttl_evict

    @data_lru.delete(key)
    @data_ttl.delete(key)

    @data_lru[key] = val
    @data_ttl[key] = Time.now.to_f

    if @data_lru.size > @max_size
      key, _ = @data_lru.first # hashes have a FIFO ordering in Ruby

      @data_ttl.delete(key)
      @data_lru.delete(key)
    end

    val
  end
end

#clearObject



56
57
58
59
60
61
# File 'lib/ldclient-rb/expiring_cache.rb', line 56

def clear
  @lock.synchronize do
    @data_lru.clear
    @data_ttl.clear
  end
end

#delete(key) ⇒ Object



47
48
49
50
51
52
53
54
# File 'lib/ldclient-rb/expiring_cache.rb', line 47

def delete(key)
  @lock.synchronize do
    ttl_evict

    @data_lru.delete(key)
    @data_ttl.delete(key)
  end
end