Skip to content

Instantly share code, notes, and snippets.

@ianks
Created June 16, 2017 18:59
Show Gist options
  • Save ianks/3e0dfec4f977f15c311e1d66ef20c541 to your computer and use it in GitHub Desktop.
Save ianks/3e0dfec4f977f15c311e1d66ef20c541 to your computer and use it in GitHub Desktop.
ThreadsafeMemoized
class ThreadsafeMemoized
def initialize
@memoized = {}
@mutex = Support::ReentrantMutex.new
end
def fetch_or_store(key)
@memoized.fetch(key) do # only first access pays for synchronization
@mutex.synchronize do
@memoized.fetch(key) { @memoized[key] = yield }
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment