Class: Cash::Lock

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

Defined Under Namespace

Classes: Error

Constant Summary collapse

DEFAULT_RETRY =
5
DEFAULT_EXPIRY =
30

Instance Method Summary collapse

Constructor Details

#initialize(cache) ⇒ Lock

Returns a new instance of Lock.



8
9
10
# File 'lib/cash/lock.rb', line 8

def initialize(cache)
  @cache = cache
end

Instance Method Details

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

Raises:



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

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



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

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

#release_lock(key) ⇒ Object



37
38
39
# File 'lib/cash/lock.rb', line 37

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

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



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

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