class Sfn::Cache::LocalLock
Simple lock for memory cache
Attributes
_key[R]
@return [Symbol] key name
_lock[R]
@return [Mutex] underlying lock
_timeout[R]
@return [Numeric] timeout
Public Class Methods
new(name, args = {})
click to toggle source
Create new instance
@param name [Symbol] name of lock @param args [Hash] @option args [Numeric] :timeout
# File lib/sfn/cache.rb, line 301 def initialize(name, args = {}) @_key = name @_timeout = args.fetch(:timeout, -1).to_f @_lock = Mutex.new end
Public Instance Methods
clear()
click to toggle source
Clear the lock
@note this is a noop
# File lib/sfn/cache.rb, line 335 def clear # noop end
lock() { || ... }
click to toggle source
Aquire lock and yield
@yield block to execute within lock @return [Object] result of yield
# File lib/sfn/cache.rb, line 311 def lock locked = false attempt_start = Time.now.to_f while (!locked && (_timeout < 0 || Time.now.to_f - attempt_start < _timeout)) locked = _lock.try_lock end if locked begin yield ensure _lock.unlock if _lock.locked? end else if defined?(Redis) raise Redis::Lock::LockTimeout.new "Timeout on lock #{_key} exceeded #{_timeout} sec" else raise LocalLockTimeout.new "Timeout on lock #{_key} exceeded #{_timeout} sec" end end end