Class: ExcessFlow::GlobalMutex

Inherits:
Object
  • Object
show all
Defined in:
lib/excess_flow/global_mutex.rb

Overview

ExcessFlow::GlobalMutex

Attempts to set up exclusive lock to execute a block of code. If another lock is in place then GlobalMutex will wait till lock is available. Always returns result of execution. GlobalMutex does not guarantee order of execution; it will only guarantee that only one thread for a given lock_key is running to avoid race conditions.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lock_key) ⇒ GlobalMutex

Returns a new instance of GlobalMutex.



32
33
34
# File 'lib/excess_flow/global_mutex.rb', line 32

def initialize(lock_key)
  @lock_key = lock_key
end

Instance Attribute Details

#lock_keyObject (readonly)

Returns the value of attribute lock_key.



26
27
28
# File 'lib/excess_flow/global_mutex.rb', line 26

def lock_key
  @lock_key
end

Class Method Details

.locked(lock_key:, &block) ⇒ Object



28
29
30
# File 'lib/excess_flow/global_mutex.rb', line 28

def self.locked(lock_key:, &block)
  new(lock_key).locked(&block)
end

Instance Method Details

#locked(&block) ⇒ Object



36
37
38
39
40
41
42
# File 'lib/excess_flow/global_mutex.rb', line 36

def locked(&block)
  sleep(ExcessFlow::MUTEX_SLEEP_TIME) until lock
  result = block.call
  unlock

  result
end