Skip to content

Commit

Permalink
Make Sprockets::Cache::MemoryStore thread-safe by using a Mutex
Browse files Browse the repository at this point in the history
  • Loading branch information
eregon committed Dec 19, 2022
1 parent 4e74e3a commit 9d461f1
Showing 1 changed file with 20 additions and 11 deletions.
31 changes: 20 additions & 11 deletions lib/sprockets/cache/memory_store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ class MemoryStore
def initialize(max_size = DEFAULT_MAX_SIZE)
@max_size = max_size
@cache = {}
@mutex = Mutex.new
end

# Public: Retrieve value from cache.
Expand All @@ -32,12 +33,14 @@ def initialize(max_size = DEFAULT_MAX_SIZE)
#
# Returns Object or nil or the value is not set.
def get(key)
exists = true
value = @cache.delete(key) { exists = false }
if exists
@cache[key] = value
else
nil
@mutex.synchronize do
exists = true
value = @cache.delete(key) { exists = false }
if exists
@cache[key] = value
else
nil
end
end
end

Expand All @@ -50,24 +53,30 @@ def get(key)
#
# Returns Object value.
def set(key, value)
@cache.delete(key)
@cache[key] = value
@cache.shift if @cache.size > @max_size
@mutex.synchronize do
@cache.delete(key)
@cache[key] = value
@cache.shift if @cache.size > @max_size
end
value
end

# Public: Pretty inspect
#
# Returns String.
def inspect
"#<#{self.class} size=#{@cache.size}/#{@max_size}>"
@mutex.synchronize do
"#<#{self.class} size=#{@cache.size}/#{@max_size}>"
end
end

# Public: Clear the cache
#
# Returns true
def clear(options=nil)
@cache.clear
@mutex.synchronize do
@cache.clear
end
true
end
end
Expand Down

0 comments on commit 9d461f1

Please sign in to comment.