Class: SizedThreadSafeHash
- Inherits:
-
Object
- Object
- SizedThreadSafeHash
- Defined in:
- lib/mqrpc/sizedhash.rb
Overview
Thread-safe sized hash similar to SizedQueue. The only time we will block execution is in setting new items. That is, SizedThreadSafeHash#[]=
Instance Method Summary collapse
-
#[](key) ⇒ Object
get an value by key.
-
#[]=(key, value) ⇒ Object
set a key and value.
-
#delete(key) ⇒ Object
delete a key.
-
#full? ⇒ Boolean
boolean, indicates true when the hash is full (has size == initialized size).
-
#has_key?(key) ⇒ Boolean
(also: #include?)
boolean, does the hash have a given key?.
-
#initialize(size) ⇒ SizedThreadSafeHash
constructor
A new instance of SizedThreadSafeHash.
-
#keys ⇒ Object
Return an array of keys for this hash.
-
#size ⇒ Object
(also: #length)
return the size (total number of entries) in this hash.
Constructor Details
#initialize(size) ⇒ SizedThreadSafeHash
Returns a new instance of SizedThreadSafeHash.
8 9 10 11 12 13 |
# File 'lib/mqrpc/sizedhash.rb', line 8 def initialize(size) @lock = Mutex.new @size = size @condvar = ConditionVariable.new @data = Hash.new end |
Instance Method Details
#[](key) ⇒ Object
get an value by key
31 32 33 34 35 |
# File 'lib/mqrpc/sizedhash.rb', line 31 def [](key) @lock.synchronize do return @data[key] end end |
#[]=(key, value) ⇒ Object
set a key and value
16 17 18 19 20 21 22 23 24 25 26 27 28 |
# File 'lib/mqrpc/sizedhash.rb', line 16 def []=(key, value) @lock.synchronize do # If adding a new item, wait if the hash is full if !@data.has_key?(key) and _withlock_full? MQRPC::logger.info "#{self}: Waiting to add key #{key.inspect}, hash is full" #MQRPC::logger.info "#{self}: Keys: #{@data.keys.inspect}" #MQRPC::logger.info "#{self} current thread is #{Thread.current}" #pp @data @condvar.wait(@lock) end @data[key] = value end end |
#delete(key) ⇒ Object
delete a key
47 48 49 50 51 52 53 54 55 56 |
# File 'lib/mqrpc/sizedhash.rb', line 47 def delete(key) @lock.synchronize do was_full = _withlock_full? @data.delete(key) if was_full MQRPC::logger.info "#{self}: signalling non-fullness" @condvar.signal end end end |
#full? ⇒ Boolean
boolean, indicates true when the hash is full (has size == initialized size)
59 60 61 62 63 |
# File 'lib/mqrpc/sizedhash.rb', line 59 def full? @lock.synchronize do return _withlock_full? end end |
#has_key?(key) ⇒ Boolean Also known as: include?
boolean, does the hash have a given key?
38 39 40 41 42 |
# File 'lib/mqrpc/sizedhash.rb', line 38 def has_key?(key) @lock.synchronize do return @data.has_key?(key) end end |
#keys ⇒ Object
Return an array of keys for this hash.
73 74 75 76 77 |
# File 'lib/mqrpc/sizedhash.rb', line 73 def keys @lock.synchronize do return @data.keys end end |
#size ⇒ Object Also known as: length
return the size (total number of entries) in this hash.
66 67 68 69 70 |
# File 'lib/mqrpc/sizedhash.rb', line 66 def size @lock.synchronize do return @data.size end end |