Class: NoBrainer::ReentrantLock

Inherits:
Lock
  • Object
show all
Defined in:
lib/no_brainer/reentrant_lock.rb

Instance Method Summary collapse

Methods inherited from Lock

#delete, find, #get_new_instance_token, #initialize, #lock, #refresh, #save?, #synchronize

Methods included from Autoload

#autoload, #autoload_and_include, #eager_autoload, #eager_load!, extended

Constructor Details

This class inherits a constructor from NoBrainer::Lock

Instance Method Details

#try_lock(options = {}) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/no_brainer/reentrant_lock.rb', line 4

def try_lock(options={})
  options.assert_valid_keys(:expire)
  set_expiration(options)

  result = NoBrainer.run do |r|
    selector.replace do |doc|
      r.branch(doc[:instance_token].default(nil).eq(self.instance_token),
               doc.merge(:expires_at => self.expires_at,
                         :lock_count => doc[:lock_count] + 1),
               r.branch(doc.eq(nil).or(doc[:expires_at] < r.now),
                        self.attributes.merge(:lock_count => 1), doc))
    end
  end

  @locked = true # to make refresh() and synchronize() happy, somewhat hacky
  return (result['inserted'] + result['replaced']) == 1
end

#unlockObject



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/no_brainer/reentrant_lock.rb', line 22

def unlock
  set_expiration(:use_previous_expire => true)

  result = NoBrainer.run do |r|
    selector.replace do |doc|
      r.branch(doc[:instance_token].default(nil).eq(self.instance_token),
               r.branch(doc[:lock_count] > 1,
                        doc.merge(:expires_at => self.expires_at,
                                  :lock_count => doc[:lock_count] - 1), nil), doc)
    end
  end

  raise_lost_lock! unless (result['deleted'] + result['replaced']) == 1
end