Skip to content

Instantly share code, notes, and snippets.

@havenwood

havenwood/foo.rb Secret

Created August 2, 2020 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/c599b9d2b8e99e7edc849ef20ec9032e to your computer and use it in GitHub Desktop.
Save havenwood/c599b9d2b8e99e7edc849ef20ec9032e to your computer and use it in GitHub Desktop.
@cached_value = nil
@value_cached = false
@mutex = Mutex.new
def expensive_calculation
sleep 5
42
end
def foo
return @cached_value if @value_cached
@mutex.synchronize do
return @cached_value if @value_cached
@cached_value = expensive_calculation
@value_cached = true
return @cached_value
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment