lib/rufus/lru.rb in rufus-lru-1.0.4 vs lib/rufus/lru.rb in rufus-lru-1.0.5

- old
+ new

@@ -20,15 +20,17 @@ # THE SOFTWARE. # # "made in Japan" #++ +require 'thread' + module Rufus module Lru - VERSION = '1.0.4' + VERSION = '1.0.5' # # A Hash that has a max size. After the maxsize has been reached, the # least recently used entries (LRU hence), will be discared to make # room for the new entries. @@ -44,11 +46,12 @@ # # h[:newer] = "b" # # puts h.inspect # >> {:newer=>"b", 3=>"aaa", 4=>"aaaa"} # - # Nota bene: this class is not threadsafe. + # Nota bene: this class is not thread-safe. If you need something thread-safe, + # use Rufus::Lru::SynchronizedHash. # class Hash < ::Hash attr_reader :maxsize attr_reader :lru_keys @@ -139,11 +142,36 @@ while size >= @maxsize delete(@lru_keys.delete_at(0)) end end end + + # + # A thread-safe version of the lru hash. + # + class SynchronizedHash < Hash + + def initialize(maxsize) + + super + @mutex = Mutex.new + end + + def [](key) + + @mutex.synchronize { super } + end + + def []=(key, value) + + @mutex.synchronize { super } + end + end end end -class LruHash < Rufus::Lru::Hash -end + +# +# The original LruHash class, kept for backward compatibility. +# +class LruHash < Rufus::Lru::Hash; end