Created
June 16, 2017 18:59
-
-
Save ianks/3e0dfec4f977f15c311e1d66ef20c541 to your computer and use it in GitHub Desktop.
ThreadsafeMemoized
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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