Class: Istox::Lock

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
lib/istox/models/lock.rb

Class Method Summary collapse

Class Method Details

.acquire(name) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/istox/models/lock.rb', line 4

def self.acquire(name)
  already_acquired = definitely_acquired?(name)

  if already_acquired
    yield
  else
    begin
      create(:name => name) unless find_by_name(name)
    rescue ActiveRecord::StatementInvalid
      # concurrent create is okay
    end

    begin
      result = nil

      transaction do
        find_by_name(name, :lock => true) # this is the call that will block
        acquired_lock(name)
        result = yield
      end

      result
    ensure
      maybe_released_lock(name) 
    end
  end
end

.definitely_acquired?(name) ⇒ Boolean

if true, the lock is acquired if false, the lock might still be acquired, because we were in another db transaction

Returns:

  • (Boolean)


34
35
36
# File 'lib/istox/models/lock.rb', line 34

def self.definitely_acquired?(name)
  !!Thread.current[:definitely_acquired_locks] and Thread.current[:definitely_acquired_locks].has_key?(name)
end