Class: Cyc::Cache
- Inherits:
-
Object
- Object
- Cyc::Cache
- Defined in:
- lib/cyc/cache.rb
Instance Method Summary collapse
-
#cached_value(key) ⇒ Object
Get cached value of a key or generate new one using given block.
-
#clear ⇒ Object
Clear the cache.
-
#initialize ⇒ Cache
constructor
A new instance of Cache.
Constructor Details
#initialize ⇒ Cache
Returns a new instance of Cache.
6 7 8 9 10 11 |
# File 'lib/cyc/cache.rb', line 6 def initialize @soft_references = Ref::SoftValueMap.new @hard_references = {} @in_progress = {} @lock = Mutex.new end |
Instance Method Details
#cached_value(key) ⇒ Object
Get cached value of a key or generate new one using given block
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/cyc/cache.rb', line 14 def cached_value(key) monitor = value = nil @lock.synchronize do if @hard_references.has_key?(key) return @hard_references[key] elsif (value = @soft_references[key]) return value elsif (monitor = @in_progress[key]) monitor.wait(@lock) return self[key] end @in_progress[key] = monitor = ConditionVariable.new end begin value = yield value_set = true ensure @lock.synchronize do self[key] = value if value_set @in_progress.delete key monitor.broadcast end end value end |
#clear ⇒ Object
Clear the cache.
41 42 43 44 45 46 |
# File 'lib/cyc/cache.rb', line 41 def clear @lock.synchronize do @soft_references.clear @hard_references.clear end end |