Class: Cash::Lock

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

Defined Under Namespace

Classes: Error

Constant Summary collapse

INITIAL_WAIT =
2
DEFAULT_RETRY =
8
DEFAULT_EXPIRY =
30

Instance Method Summary collapse

Constructor Details

#initialize(cache) ⇒ Lock

Returns a new instance of Lock.



11
12
13
# File 'lib/cash/lock.rb', line 11

def initialize(cache)
  @cache = cache
end

Instance Method Details

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

Raises:



28
29
30
31
32
33
34
35
36
37
# File 'lib/cash/lock.rb', line 28

def acquire_lock(key, lock_expiry = DEFAULT_EXPIRY, retries = DEFAULT_RETRY, initial_wait = INITIAL_WAIT)
  retries.times do |count|
    response = @cache.add("lock/#{key}", host_pid, lock_expiry)
    return if response == "STORED\r\n"
    return if recursive_lock?(key)
    exponential_sleep(count, initial_wait) unless count == retries - 1
  end
  debug_lock(key)
  raise Error, "Couldn't acquire memcache lock on 'lock/#{key}'"
end

#exponential_sleep(count, initial_wait) ⇒ Object



43
44
45
# File 'lib/cash/lock.rb', line 43

def exponential_sleep(count, initial_wait)
  sleep((2**count) * initial_wait)
end

#release_lock(key) ⇒ Object



39
40
41
# File 'lib/cash/lock.rb', line 39

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

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



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/cash/lock.rb', line 15

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