Class: AtomicMemCacheStore

Inherits:
ActiveSupport::Cache::MemCacheStore
  • Object
show all
Defined in:
lib/atomic_mem_cache_store.rb

Constant Summary collapse

VERSION =
File.read(File.join(File.dirname(__FILE__),'..','VERSION') ).strip
NEWLY_STORED =
"STORED\r\n"

Class Attribute Summary collapse

Instance Method Summary collapse

Class Attribute Details

.grace_periodObject

Returns the value of attribute grace_period.



7
8
9
# File 'lib/atomic_mem_cache_store.rb', line 7

def grace_period
  @grace_period
end

Instance Method Details

#read(key, options = nil) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/atomic_mem_cache_store.rb', line 10

def read(key, options = nil)
  result = super
  
  if result.present?
    timer_key = timer_key(key)
    #check whether the cache is expired
    if @data.get(timer_key, true).nil?
      #optimistic lock to avoid concurrent recalculation
      if @data.add(timer_key, '', self.class.grace_period, true) == NEWLY_STORED
        #trigger cache recalculation
        return handle_expired_read(key,result)
      end
      #already recalculated or expirated in another process/thread
    end
    #key not expired
  end
  result
end

#write(key, value, options = nil) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/atomic_mem_cache_store.rb', line 29

def write(key, value, options = nil)
  expiry = (options && options[:expires_in]) || 0
  #extend write expiration period and reset expiration timer
  options[:expires_in] = expiry + 2*self.class.grace_period unless expiry.zero?
  @data.set(timer_key(key), '', expiry, true)
  super
end