Skip to content
Browse files

a sensible lru

  • Loading branch information...
1 parent 6abbb13 commit fd7b9e466c9646698dd0836e2630f55a3054a1ea Nick Kallen committed Apr 20, 2009
Showing with 28 additions and 18 deletions.
  1. +5 −2 joke_server.rb
  2. +21 −16 util/in_process_lru_cache.rb
  3. +2 −0 util/statosaurus.rb
View
7 joke_server.rb
@@ -19,14 +19,17 @@
module JokeServer
include LineBufferedConnection
- extend InProcessLRUCache
+
+ def self.cache
+ @cache ||= InProcessLRUCache.new(2)
+ end
def receive_line(line)
$stats.transaction do
data, source_transaction_id = line.split(';')
$stats.set('source_transaction_id', source_transaction_id)
$stats.measure('job') do
- result = JokeServer.get(data) do
+ result = JokeServer.cache.get(data) do
100000.times { Time.now }
sleep rand
"KNOCK KNOCK: #{data}\n"
View
37 util/in_process_lru_cache.rb
@@ -1,20 +1,25 @@
-module InProcessLRUCache
- def get(data)
- @cache ||= []
- cache_hit = @cache.detect do |key, value|
- data == key
- end
- if !cache_hit
- $stats.set('cache_hit', 0)
-
- result = yield(data)
- @cache.unshift([data, result])
- @cache.slice!(2..-1)
- result
- else
- $stats.set('cache_hit', 1)
+class InProcessLRUCache
+ def initialize(max_keys)
+ @max_keys = max_keys
+ end
+
+ def get(key)
+ @cache ||= {}
+ @lru ||= []
+
+ @lru << key
- cache_hit[1]
+ result = @cache[key]
+ $stats.set('cache_hit', !!result)
+ if !result
+ free_least_recently_used_item
+ result = @cache[key] = yield(key) if block_given?
end
+ result
+ end
+
+ private
+ def free_least_recently_used_item
+ @cache.delete(@lru.shift) if @cache.size >= @max_keys
end
end
View
2 util/statosaurus.rb
@@ -55,6 +55,8 @@ def format(value)
"-"
when Float
"%f" % value
+ when TrueClass, FalseClass
+ value ? '1' : 0
else
value.to_s
end

0 comments on commit fd7b9e4

Please sign in to comment.
Something went wrong with that request. Please try again.