Class: SynchronizedHash
- Defined in:
- lib/adhearsion/foundation/synchronized_hash.rb
Overview
Implementation of a Thread-safe Hash. Works by delegating methods to a Hash behind-the-scenes after obtaining an exclusive # lock. Use exactly as you would a normal Hash.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(*args, &block) ⇒ SynchronizedHash
constructor
A new instance of SynchronizedHash.
-
#with_lock {|Hash| ... } ⇒ Object
If you need to do many operations atomically (a la transaction), you can call this method and access the yielded Hash which can be safely modified for the duration of your block.
Constructor Details
#initialize(*args, &block) ⇒ SynchronizedHash
Returns a new instance of SynchronizedHash.
81 82 83 84 |
# File 'lib/adhearsion/foundation/synchronized_hash.rb', line 81 def initialize(*args, &block) @delegate = Hash.new(*args, &block) @lock = Mutex.new end |
Class Method Details
.atomically_delegate(method_name) ⇒ Object
6 7 8 9 10 11 12 13 14 |
# File 'lib/adhearsion/foundation/synchronized_hash.rb', line 6 def self.atomically_delegate(method_name) class_eval(<<-RUBY, __FILE__, __LINE__) def #{method_name}(*args, &block) @lock.synchronize do @delegate.send(#{method_name.inspect}, *args, &block) end end RUBY end |
Instance Method Details
#with_lock {|Hash| ... } ⇒ Object
If you need to do many operations atomically (a la transaction), you can call this method and access the yielded Hash which can be safely modified for the duration of your block.
92 93 94 |
# File 'lib/adhearsion/foundation/synchronized_hash.rb', line 92 def with_lock(&block) @lock.synchronize { yield @delegate } end |