Module: AtomicStore

Included in:
AtomicDalliStore, AtomicMemCacheStore
Defined in:
lib/atomic_store.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



11
12
13
14
# File 'lib/atomic_store.rb', line 11

def self.included(base)
  @raw_arg = base::RAW_ARG
  base.extend(ClassMethods)
end

Instance Method Details

#read(key, options = nil) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/atomic_store.rb', line 16

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, @raw_arg) == 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



35
36
37
38
39
40
41
# File 'lib/atomic_store.rb', line 35

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, @raw_arg)
  super
end