lib/memoizable/memory.rb in memoizable-0.3.0 vs lib/memoizable/memory.rb in memoizable-0.3.1
- old
+ new
@@ -9,11 +9,12 @@
#
# @return [undefined]
#
# @api private
def initialize
- @memory = ThreadSafe::Cache.new
+ @memory = ThreadSafe::Cache.new
+ @monitor = Monitor.new
freeze
end
# Get the value from memory
#
@@ -51,23 +52,17 @@
#
# @yieldreturn [Object]
# the value to memoize
#
# @api public
- def fetch(name, &block)
- @memory.compute_if_absent(name, &block)
- end
-
- # Set the memory
- #
- # @param [Hash]
- #
- # @return [Memory]
- #
- # @api public
- def set(data)
- data.each { |name, value| self[name] = value }
- self
+ def fetch(name)
+ @memory.fetch(name) do # check for the key
+ @monitor.synchronize do # acquire a lock if the key is not found
+ @memory.fetch(name) do # recheck under lock
+ self[name] = yield # set the value
+ end
+ end
+ end
end
# Test if the name has a value in memory
#
# @param [Symbol] name