Class: SoftEvictCache::SingleValueCache

Inherits:
Object
  • Object
show all
Defined in:
lib/soft_evict_cache/single_value_cache.rb

Defined Under Namespace

Classes: Entry

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(soft_evict, hard_evict, next_value) ⇒ SingleValueCache

Returns a new instance of SingleValueCache.



19
20
21
22
23
24
# File 'lib/soft_evict_cache/single_value_cache.rb', line 19

def initialize(soft_evict, hard_evict, next_value)
  @soft_evict = soft_evict
  @hard_evict = hard_evict
  @next_value = next_value
  @agent = Concurrent::Agent.new(Entry.new(nil, Time.now - 1, Time.now - 1))
end

Class Method Details

.build(soft_evict, hard_evict, &next_value) ⇒ Object



4
5
6
# File 'lib/soft_evict_cache/single_value_cache.rb', line 4

def build(soft_evict, hard_evict, &next_value)
  new(soft_evict, hard_evict, next_value)
end

Instance Method Details

#update_entry(old_entry) ⇒ Object



26
27
28
29
30
# File 'lib/soft_evict_cache/single_value_cache.rb', line 26

def update_entry(old_entry)
  return old_entry unless old_entry.soft_evicted?
  value = @next_value.call
  Entry.new(value, Time.now + @soft_evict, Time.now + @hard_evict)
end

#valueObject



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/soft_evict_cache/single_value_cache.rb', line 32

def value
  current_entry = @agent.value
  if current_entry.valid?
    @agent.send { |old_entry| update_entry(old_entry) } if current_entry.soft_evicted?
    current_entry.value
  else
    promise = Concurrent::Promise.new
    @agent.send do |old_entry|
      new_entry = update_entry(old_entry)
      promise.set(new_entry.value)
      new_entry
    end
    promise.value
  end
end