Class: Cyc::Cache

Inherits:
Object
  • Object
show all
Defined in:
lib/cyc/cache.rb

Instance Method Summary collapse

Constructor Details

#initializeCache

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

#[](key) ⇒ Object

Get a value from cache.



37
38
39
40
41
42
43
# File 'lib/cyc/cache.rb', line 37

def [](key)
  if @hard_references.has_key?(key)
    @hard_references[key]
  else
    @soft_references[key]
  end
end

#[]=(key, value) ⇒ Object

Put a value for a given key to the cache.



46
47
48
49
50
51
52
53
54
55
# File 'lib/cyc/cache.rb', line 46

def []=(key,value)
  case value
  when TrueClass,FalseClass,NilClass,Fixnum,::Symbol
    @soft_references.delete(key)
    @hard_references[key] = value
  else
    @hard_references.delete(key)
    @soft_references[key] = value
  end
end

#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
# 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
  value = yield
  @lock.synchronize do
    self[key] = value
    @in_progress.delete key
    monitor.broadcast
  end
  value
end

#clearObject

Clear the cache.



58
59
60
61
62
63
# File 'lib/cyc/cache.rb', line 58

def clear
  @lock.synchronize do
    @soft_references.clear
    @hard_references.clear
  end
end