Class: TRuby::MemoryCache

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

Overview

In-memory LRU cache

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(max_size: 1000) ⇒ MemoryCache

Returns a new instance of MemoryCache.



44
45
46
47
48
49
50
51
# File 'lib/t_ruby/cache.rb', line 44

def initialize(max_size: 1000)
  @max_size = max_size
  @cache = {}
  @access_order = []
  @hits = 0
  @misses = 0
  @mutex = Mutex.new
end

Instance Attribute Details

#hitsObject (readonly)

Returns the value of attribute hits.



42
43
44
# File 'lib/t_ruby/cache.rb', line 42

def hits
  @hits
end

#max_sizeObject (readonly)

Returns the value of attribute max_size.



42
43
44
# File 'lib/t_ruby/cache.rb', line 42

def max_size
  @max_size
end

#missesObject (readonly)

Returns the value of attribute misses.



42
43
44
# File 'lib/t_ruby/cache.rb', line 42

def misses
  @misses
end

Instance Method Details

#clearObject



83
84
85
86
87
88
89
90
# File 'lib/t_ruby/cache.rb', line 83

def clear
  @mutex.synchronize do
    @cache.clear
    @access_order.clear
    @hits = 0
    @misses = 0
  end
end

#delete(key) ⇒ Object



76
77
78
79
80
81
# File 'lib/t_ruby/cache.rb', line 76

def delete(key)
  @mutex.synchronize do
    @cache.delete(key)
    @access_order.delete(key)
  end
end

#get(key) ⇒ Object



53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/t_ruby/cache.rb', line 53

def get(key)
  @mutex.synchronize do
    if @cache.key?(key)
      @hits += 1
      touch(key)
      @cache[key].access
    else
      @misses += 1
      nil
    end
  end
end

#hit_rateObject



96
97
98
99
100
# File 'lib/t_ruby/cache.rb', line 96

def hit_rate
  total = @hits + @misses
  return 0.0 if total.zero?
  @hits.to_f / total
end

#set(key, value) ⇒ Object



66
67
68
69
70
71
72
73
74
# File 'lib/t_ruby/cache.rb', line 66

def set(key, value)
  @mutex.synchronize do
    evict if @cache.size >= @max_size && !@cache.key?(key)

    @cache[key] = CacheEntry.new(key, value)
    touch(key)
    value
  end
end

#sizeObject



92
93
94
# File 'lib/t_ruby/cache.rb', line 92

def size
  @cache.size
end

#statsObject



102
103
104
105
106
107
108
109
110
# File 'lib/t_ruby/cache.rb', line 102

def stats
  {
    size: size,
    max_size: @max_size,
    hits: @hits,
    misses: @misses,
    hit_rate: hit_rate
  }
end