Class: MemcacheLock

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

Defined Under Namespace

Classes: Error

Constant Summary collapse

DEFAULT_RETRY =
5
DEFAULT_EXPIRY =
30

Instance Method Summary collapse

Constructor Details

#initialize(cache) ⇒ MemcacheLock

Returns a new instance of MemcacheLock.



7
8
9
# File 'lib/memcache-lock.rb', line 7

def initialize(cache)
  @cache = cache
end

Instance Method Details

#acquire_lock(key, lock_expiry = DEFAULT_EXPIRY, retries = DEFAULT_RETRY) ⇒ Object

Raises:



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/memcache-lock.rb', line 24

def acquire_lock(key, lock_expiry = DEFAULT_EXPIRY, retries = DEFAULT_RETRY)
  retries.times do |count|
    begin
      response = @cache.add("lock/#{key}", Process.pid, lock_expiry)
      return if response == "STORED\r\n"
      raise Error if count == retries - 1
    end
    exponential_sleep(count) unless count == retries - 1
  end
  raise Error, "Couldn't acquire memcache lock for: #{key}"
end

#exponential_sleep(count) ⇒ Object



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

def exponential_sleep(count)
  @runtime += Benchmark::measure { sleep((2**count) / 2.0) }
end

#release_lock(key) ⇒ Object



36
37
38
# File 'lib/memcache-lock.rb', line 36

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

#synchronize(key, lock_expiry = DEFAULT_EXPIRY, retries = DEFAULT_RETRY) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/memcache-lock.rb', line 11

def synchronize(key, lock_expiry = DEFAULT_EXPIRY, retries = DEFAULT_RETRY)
  if recursive_lock?(key)
    yield
  else
    acquire_lock(key, lock_expiry, retries)
    begin
      yield
    ensure
      release_lock(key)
    end
  end
end