Class: MemcacheLock

Inherits:
Object
  • Object
show all
Defined in:
lib/memcache-lock.rb

Defined Under Namespace

Classes: Error

Constant Summary collapse

DEFAULT_OPTIONS =
{
  :initial_wait => 10e-3, # seconds -- first soft fail will wait for 10ms
  :expiry       => 60,    # seconds
  :retries      => 11,    # these defaults will retry for a total 41sec max
}

Instance Method Summary collapse

Constructor Details

#initialize(cache) ⇒ MemcacheLock

Returns a new instance of MemcacheLock.



13
14
15
# File 'lib/memcache-lock.rb', line 13

def initialize(cache)
  @cache = cache
end

Instance Method Details

#acquire_lock(key, options = {}) ⇒ Object

Raises:



30
31
32
33
34
35
36
37
38
39
# File 'lib/memcache-lock.rb', line 30

def acquire_lock(key, options={})
  options = DEFAULT_OPTIONS.merge(options)
  1.upto(options[:retries]) do |attempt|
    response = @cache.add("lock/#{key}", uid, options[:expiry])
    return if response == "STORED\r\n"
    break if attempt == options[:retries]
    Kernel.sleep(2 ** (attempt + rand - 1) * options[:initial_wait])
  end
  raise Error, "Couldn't acquire memcache lock for: #{key}"
end

#release_lock(key) ⇒ Object



41
42
43
# File 'lib/memcache-lock.rb', line 41

def release_lock(key)
  @cache.delete("lock/#{key}")
end

#synchronize(key, options = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/memcache-lock.rb', line 17

def synchronize(key, options={})
  if acquired?(key)
    yield
  else
    acquire_lock(key, options)
    begin
      yield
    ensure
      release_lock(key)
    end
  end
end