Skip to content

Commit

Permalink
Add double checked locking to Memoizable::Memory#fetch
Browse files Browse the repository at this point in the history
* This is based on the comments in
  headius/thread_safe#15 (comment)
  on how to handle this exact issue with memoization.
  • Loading branch information
dkubb committed Dec 15, 2013
1 parent 6ace275 commit 2cd167d
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
1 change: 1 addition & 0 deletions lib/memoizable.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# encoding: utf-8

require 'monitor'
require 'thread_safe'

require 'memoizable/instance_methods'
Expand Down
13 changes: 10 additions & 3 deletions lib/memoizable/memory.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ class Memory
#
# @api private
def initialize
@memory = ThreadSafe::Cache.new
@memory = ThreadSafe::Cache.new
@monitor = Monitor.new
freeze
end

Expand Down Expand Up @@ -53,8 +54,14 @@ def []=(name, value)
# the value to memoize
#
# @api public
def fetch(name, &block)
@memory.compute_if_absent(name, &block)
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

# Set the memory
Expand Down

0 comments on commit 2cd167d

Please sign in to comment.