Method: Cyc::Cache#cached_value

Defined in:
lib/cyc/cache.rb

#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