Class: RemoteLock

Inherits:
Object
  • Object
show all
Defined in:
lib/remote_lock.rb,
lib/remote_lock/version.rb

Defined Under Namespace

Modules: Adapters 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
}
VERSION =
"1.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(adapter, prefix = nil) ⇒ RemoteLock

Returns a new instance of RemoteLock.



10
11
12
13
14
# File 'lib/remote_lock.rb', line 10

def initialize(adapter, prefix = nil)
  raise "Invalid Adapter" unless Adapters::Base.valid?(adapter)
  @adapter = adapter
  @prefix = prefix
end

Instance Method Details

#acquire_lock(key, options = {}) ⇒ Object

Raises:



29
30
31
32
33
34
35
36
37
38
# File 'lib/remote_lock.rb', line 29

def acquire_lock(key, options = {})
  options = DEFAULT_OPTIONS.merge(options)
  1.upto(options[:retries]) do |attempt|
    success = @adapter.store(key_for(key), options[:expiry])
    return if success
    break if attempt == options[:retries]
    Kernel.sleep(2 ** (attempt + rand - 1) * options[:initial_wait])
  end
  raise RemoteLock::Error, "Couldn't acquire lock for: #{key}"
end

#acquired?(key) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
# File 'lib/remote_lock.rb', line 44

def acquired?(key)
  @adapter.has_key?(key_for(key))
end

#release_lock(key) ⇒ Object



40
41
42
# File 'lib/remote_lock.rb', line 40

def release_lock(key)
  @adapter.delete(key_for(key))
end

#synchronize(key, options = {}) ⇒ Object



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

def synchronize(key, options={})
  if acquired?(key)
    yield
  else
    acquire_lock(key, options)
    begin
      yield
    ensure
      release_lock(key)
    end
  end
end