Class: Blodsband::Riak::Lock

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(bucket, key) ⇒ Lock

Create a new lock in a bucket.

Parameters:

  • bucket (Blodsband::Riak::Bucket)

    the bucket in which the lock shall live.

  • key (String)

    the key to the lock



16
17
18
19
# File 'lib/blodsband/riak/lock.rb', line 16

def initialize(bucket, key)
  @bucket = bucket
  @key = key
end

Instance Attribute Details

#keyObject (readonly)

Returns the value of attribute key.



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

def key
  @key
end

Instance Method Details

#lock(timeout = 1 << 256) ⇒ true, false

Lock this lock, with an optional timeout

Parameters:

  • timeout (Number) (defaults to: 1 << 256)

    the maximum time to wait for the lock to be available, in seconds.

Returns:

  • (true, false)

    whether we succeeded in locking before the timeout



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

def lock(timeout = 1 << 256)
  deadline = Time.now.to_f + timeout
  while !@bucket.put_if_missing(key, "locked")
    EM::Synchrony.sleep(0.1)
    if Time.now.to_f > deadline
      return false
    end
  end
  return true
end

#synchronize(&block) ⇒ Object

Execute a block while exclusively locking this lock.

Parameters:

  • block (Block)

    the block to execute.



55
56
57
58
59
60
61
62
# File 'lib/blodsband/riak/lock.rb', line 55

def synchronize(&block)
  lock
  begin
    yield
  ensure
    unlock
  end
end

#unlockObject

Unlock this lock



42
43
44
45
46
47
48
# File 'lib/blodsband/riak/lock.rb', line 42

def unlock
  @bucket.delete(key, :riak_params => {:w => :all})
  while !@bucket.get(key, :unique => true).nil?
    EM::Synchrony.sleep(0.1)
    @bucket.delete(key, :riak_params => {:w => :all})
  end
end