Class: RedisReadWriteLocks::BaseLock
- Inherits:
-
Object
- Object
- RedisReadWriteLocks::BaseLock
- Defined in:
- lib/redis_read_write_locks/base_lock.rb
Constant Summary collapse
- DEFAULT_TTL =
30- RETRY_INTERVAL =
0.01
Instance Attribute Summary collapse
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#token ⇒ Object
readonly
Returns the value of attribute token.
Instance Method Summary collapse
-
#acquire(timeout: nil) ⇒ Object
Non-blocking: returns true/false.
- #acquired? ⇒ Boolean
-
#initialize(redis:, name:, ttl: DEFAULT_TTL) ⇒ BaseLock
constructor
A new instance of BaseLock.
-
#synchronize(timeout: nil, &block) ⇒ Object
Acquires lock, yields, releases.
Constructor Details
#initialize(redis:, name:, ttl: DEFAULT_TTL) ⇒ BaseLock
Returns a new instance of BaseLock.
10 11 12 13 14 15 16 |
# File 'lib/redis_read_write_locks/base_lock.rb', line 10 def initialize(redis:, name:, ttl: DEFAULT_TTL) @redis = redis @name = name @ttl = ttl @token = SecureRandom.uuid @acquired = false end |
Instance Attribute Details
#name ⇒ Object (readonly)
Returns the value of attribute name.
8 9 10 |
# File 'lib/redis_read_write_locks/base_lock.rb', line 8 def name @name end |
#token ⇒ Object (readonly)
Returns the value of attribute token.
8 9 10 |
# File 'lib/redis_read_write_locks/base_lock.rb', line 8 def token @token end |
Instance Method Details
#acquire(timeout: nil) ⇒ Object
Non-blocking: returns true/false. With timeout: retries for timeout seconds, returns true or raises LockTimeoutError.
24 25 26 27 28 29 30 31 32 33 |
# File 'lib/redis_read_write_locks/base_lock.rb', line 24 def acquire(timeout: nil) return try_acquire if timeout.nil? deadline = Time.now.to_f + timeout loop do return true if try_acquire raise LockTimeoutError, "Timeout acquiring #{lock_type} lock '#{@name}'" if Time.now.to_f >= deadline sleep RETRY_INTERVAL end end |
#acquired? ⇒ Boolean
18 19 20 |
# File 'lib/redis_read_write_locks/base_lock.rb', line 18 def acquired? @acquired end |
#synchronize(timeout: nil, &block) ⇒ Object
Acquires lock, yields, releases. Raises LockNotAcquiredError if non-blocking acquire fails.
36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/redis_read_write_locks/base_lock.rb', line 36 def synchronize(timeout: nil, &block) if timeout acquire(timeout: timeout) else acquire || raise(LockNotAcquiredError, "Could not acquire #{lock_type} lock '#{@name}'") end begin block.call ensure release end end |