Class: Redpear::Store::Lock
Defined Under Namespace
Classes: LockTimeout
Constant Summary
Constants inherited from Base
Base::IS_NIL, Base::IS_ONE, Base::IS_TRUE, Base::IS_ZERO, Base::PICK_FIRST, Base::TO_INT, Base::TO_SET
Instance Attribute Summary
Attributes inherited from Base
Class Method Summary collapse
-
.default_options ⇒ Hash
Default lock options.
Instance Method Summary collapse
-
#current ⇒ Float
The current lock timestamp.
-
#lock(options = {}) { ... } ⇒ Object
Creates a lock and yields a transaction.
-
#lock?(options = {}) { ... } ⇒ Boolean
Conditional locking.
-
#reserve(seconds, options = {}) { ... } ⇒ Object
Reserves a lock and yields a transaction, but only if not reserved by someone else.
-
#reserve?(seconds) ⇒ Boolean
Tries to reserve a lock.
-
#value ⇒ String
The current lock value.
Methods inherited from Base
#clear, #exists?, #expire, #expire_at, #expire_in, #initialize, #inspect, #purge!, temporary, #ttl, #type, #watch
Constructor Details
This class inherits a constructor from Redpear::Store::Base
Class Method Details
Instance Method Details
#current ⇒ Float
Returns the current lock timestamp.
18 19 20 |
# File 'lib/redpear/store/lock.rb', line 18 def current value.to_f end |
#lock(options = {}) { ... } ⇒ Object
Creates a lock and yields a transaction.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/redpear/store/lock.rb', line 47 def lock( = {}) = self.class..merge() result = nil = nil timeout = to_time([:wait_timeout]) while ! && timeout > Time.now = to_time([:lock_timeout]).to_f if lock_obtained?() || expired_lock_obtained?() result = yield else = nil # Unset sleep 0.1 end end unless raise LockTimeout, "Could not acquire lock on '#{key}'. Timed out." end result ensure purge! if && > Time.now.to_f end |
#lock?(options = {}) { ... } ⇒ Boolean
Conditional locking. Performs a transaction if lock can be acquired.
77 78 79 80 81 82 |
# File 'lib/redpear/store/lock.rb', line 77 def lock?( = {}, &block) lock(, &block) true rescue LockTimeout false end |
#reserve(seconds, options = {}) { ... } ⇒ Object
Reserves a lock and yields a transaction, but only if not reserved by someone else. This is useful when processes can be triggered by concurrent threads, but should only be executed once.
122 123 124 125 126 |
# File 'lib/redpear/store/lock.rb', line 122 def reserve(seconds, = {}) yield if reserve?(seconds) ensure purge! if [:clear] end |
#reserve?(seconds) ⇒ Boolean
Tries to reserve a lock. Low-level method, please see #reserve for the high-level API.
89 90 91 92 |
# File 'lib/redpear/store/lock.rb', line 89 def reserve?(seconds) = to_time(seconds).to_f lock_obtained?() || expired_lock_obtained?() end |
#value ⇒ String
Returns the current lock value.
23 24 25 |
# File 'lib/redpear/store/lock.rb', line 23 def value conn.get key end |