Class: Memorb::KeyValueStore
- Inherits:
-
Object
- Object
- Memorb::KeyValueStore
- Defined in:
- lib/memorb/key_value_store.rb
Instance Attribute Summary collapse
-
#lock ⇒ Object
readonly
Returns the value of attribute lock.
Instance Method Summary collapse
- #fetch(key, &fallback) ⇒ Object
- #forget(key) ⇒ Object
- #has?(key) ⇒ Boolean
-
#initialize ⇒ KeyValueStore
constructor
A new instance of KeyValueStore.
- #inspect ⇒ Object
- #keys ⇒ Object
- #read(key) ⇒ Object
- #reset! ⇒ Object
- #write(key, value) ⇒ Object
Constructor Details
#initialize ⇒ KeyValueStore
Returns a new instance of KeyValueStore.
8 9 10 11 |
# File 'lib/memorb/key_value_store.rb', line 8 def initialize @data = ::Hash.new @lock = ::Concurrent::ReentrantReadWriteLock.new end |
Instance Attribute Details
#lock ⇒ Object (readonly)
Returns the value of attribute lock.
13 14 15 |
# File 'lib/memorb/key_value_store.rb', line 13 def lock @lock end |
Instance Method Details
#fetch(key, &fallback) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/memorb/key_value_store.rb', line 27 def fetch(key, &fallback) @lock.with_read_lock do return _read(key) if _has?(key) end # Concurrent readers could all see no entry if none were able to # write before the others checked for the key, so they need to be # synchronized below to ensure that only one of them actually # executes the fallback block and writes the resulting value. @lock.with_write_lock do # The first thread to acquire the write lock will write the value # for the key causing the other aforementioned threads that may # also want to write to now see the key and return it. _has?(key) ? _read(key) : _write(key, fallback.call) end end |
#forget(key) ⇒ Object
43 44 45 |
# File 'lib/memorb/key_value_store.rb', line 43 def forget(key) @lock.with_write_lock { _forget(key) } end |
#has?(key) ⇒ Boolean
23 24 25 |
# File 'lib/memorb/key_value_store.rb', line 23 def has?(key) @lock.with_read_lock { _has?(key) } end |
#inspect ⇒ Object
55 56 57 |
# File 'lib/memorb/key_value_store.rb', line 55 def inspect "#<#{ self.class.name } keys=#{ keys.inspect }>" end |
#keys ⇒ Object
51 52 53 |
# File 'lib/memorb/key_value_store.rb', line 51 def keys @lock.with_read_lock { _keys } end |
#read(key) ⇒ Object
19 20 21 |
# File 'lib/memorb/key_value_store.rb', line 19 def read(key) @lock.with_read_lock { _read(key) } end |
#reset! ⇒ Object
47 48 49 |
# File 'lib/memorb/key_value_store.rb', line 47 def reset! @lock.with_write_lock { _reset! } end |
#write(key, value) ⇒ Object
15 16 17 |
# File 'lib/memorb/key_value_store.rb', line 15 def write(key, value) @lock.with_write_lock { _write(key, value) } end |