Class: SuperCache::Lock
- Inherits:
-
Object
- Object
- SuperCache::Lock
- Defined in:
- lib/super_cache/lock.rb
Defined Under Namespace
Classes: MaxRetriesError
Constant Summary collapse
- DEFAULT_RETRY =
5
- DEFAULT_EXPIRY =
30
Class Method Summary collapse
- .acquire_lock(key, lock_expiry = DEFAULT_EXPIRY) ⇒ Object
- .exponential_sleep(count) ⇒ Object
- .release_lock(key) ⇒ Object
- .synchronize(key, lock_expiry = DEFAULT_EXPIRY, retries = DEFAULT_RETRY) ⇒ Object
Class Method Details
.acquire_lock(key, lock_expiry = DEFAULT_EXPIRY) ⇒ Object
26 27 28 |
# File 'lib/super_cache/lock.rb', line 26 def acquire_lock(key, lock_expiry = DEFAULT_EXPIRY) Rails.cache.write("lock/#{key}", Process.pid, :unless_exist => true, :expires_in => lock_expiry) end |
.exponential_sleep(count) ⇒ Object
34 35 36 |
# File 'lib/super_cache/lock.rb', line 34 def exponential_sleep(count) Benchmark::measure { sleep((2**count) / 5.0) } end |
.release_lock(key) ⇒ Object
30 31 32 |
# File 'lib/super_cache/lock.rb', line 30 def release_lock(key) Rails.cache.delete("lock/#{key}") end |
.synchronize(key, lock_expiry = DEFAULT_EXPIRY, retries = DEFAULT_RETRY) ⇒ Object
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/super_cache/lock.rb', line 9 def synchronize(key, lock_expiry = DEFAULT_EXPIRY, retries = DEFAULT_RETRY) if recursive_lock?(key) yield else begin retries.times do |count| return yield if acquire_lock(key, lock_expiry) raise MaxRetriesError if count == retries - 1 exponential_sleep(count) unless count == retries - 1 end raise MaxRetriesError, "Couldn't acquire memcache lock for: #{key}" ensure release_lock(key) end end end |