Class: TaskJuggler::DataCache

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
lib/taskjuggler/DataCache.rb

Overview

This class provides a global data cache that can be used to store and retrieve values indexed by a key. The cache is size limited. When maximum capacity is reached, a certain percentage of the least requested values is dropped from the cache. The primary purpose of this global cache is to store values that are expensive to compute but may be need on several occasions during the program execution.

Instance Method Summary collapse

Constructor Details

#initializeDataCache

Returns a new instance of DataCache.



58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/taskjuggler/DataCache.rb', line 58

def initialize
  resize
  flush
  # Counter for the number of writes to the cache.
  @stores = 0
  # Counter for the number of found values.
  @hits = 0
  # Counter for the number of not found values.
  @misses = 0
  # Counter for hash collisions
  @collisions = 0
end

Instance Method Details

#cached(*args) ⇒ Object

args is a set of arguments that unambigously identify the data entry. It’s converted into a hash to store or recover a previously stored entry. If we have a value for the key, return the value. Otherwise call the block to compute the value, store it and return it.



91
92
93
# File 'lib/taskjuggler/DataCache.rb', line 91

def cached(*args)
  yield
end

#flushObject

Completely flush the cache. The statistic counters will remain intact, but all data values are lost.



82
83
84
# File 'lib/taskjuggler/DataCache.rb', line 82

def flush
  @entries = {}
end

#resize(size = 100000) ⇒ Object

For now, we use this randomly determined size.



72
73
74
75
76
77
78
# File 'lib/taskjuggler/DataCache.rb', line 72

def resize(size = 100000)
  @highWaterMark = size
  # Flushing out the least used entries is fairly expensive. So we only
  # want to do this once in a while. The lowWaterMark determines how much
  # of the entries will survive the flush.
  @lowWaterMark = size * 0.9
end

#to_sObject



122
123
124
125
126
127
128
# File 'lib/taskjuggler/DataCache.rb', line 122

def to_s
  <<"EOT"
Entries: #{@entries.size}   Stores: #{@stores}   Collisions: #{@collisions}
Hits: #{@hits}   Misses: #{@misses}
Hit Rate: #{@hits * 100.0 / (@hits + @misses)}%
EOT
end