Class: Sfn::Cache::LocalLock
- Inherits:
-
Object
- Object
- Sfn::Cache::LocalLock
- Defined in:
- lib/sfn/cache.rb
Overview
Simple lock for memory cache
Defined Under Namespace
Classes: LocalLockTimeout
Instance Attribute Summary collapse
-
#_key ⇒ Symbol
readonly
Key name.
-
#_lock ⇒ Mutex
readonly
Underlying lock.
-
#_timeout ⇒ Numeric
readonly
Timeout.
Instance Method Summary collapse
-
#clear ⇒ Object
Clear the lock.
-
#initialize(name, args = {}) ⇒ LocalLock
constructor
Create new instance.
-
#lock { ... } ⇒ Object
Aquire lock and yield.
Constructor Details
#initialize(name, args = {}) ⇒ LocalLock
Create new instance
303 304 305 306 307 |
# File 'lib/sfn/cache.rb', line 303 def initialize(name, args={}) @_key = name @_timeout = args.fetch(:timeout, -1).to_f @_lock = Mutex.new end |
Instance Attribute Details
#_key ⇒ Symbol (readonly)
Returns key name.
292 293 294 |
# File 'lib/sfn/cache.rb', line 292 def _key @_key end |
#_lock ⇒ Mutex (readonly)
Returns underlying lock.
296 297 298 |
# File 'lib/sfn/cache.rb', line 296 def _lock @_lock end |
#_timeout ⇒ Numeric (readonly)
Returns timeout.
294 295 296 |
# File 'lib/sfn/cache.rb', line 294 def _timeout @_timeout end |
Instance Method Details
#clear ⇒ Object
Note:
this is a noop
Clear the lock
337 338 339 |
# File 'lib/sfn/cache.rb', line 337 def clear # noop end |
#lock { ... } ⇒ Object
Aquire lock and yield
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 |
# File 'lib/sfn/cache.rb', line 313 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 |