Class: MemcacheLock
- Inherits:
-
Object
- Object
- MemcacheLock
- 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
- #acquire_lock(key, options = {}) ⇒ Object
-
#initialize(cache) ⇒ MemcacheLock
constructor
A new instance of MemcacheLock.
- #release_lock(key) ⇒ Object
- #synchronize(key, options = {}) ⇒ Object
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
30 31 32 33 34 35 36 37 38 39 |
# File 'lib/memcache-lock.rb', line 30 def acquire_lock(key, ={}) = DEFAULT_OPTIONS.merge() 1.upto([:retries]) do |attempt| response = @cache.add("lock/#{key}", uid, [:expiry]) return if response == "STORED\r\n" break if attempt == [:retries] Kernel.sleep(2 ** (attempt + rand - 1) * [: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, ={}) if acquired?(key) yield else acquire_lock(key, ) begin yield ensure release_lock(key) end end end |