From 9d461f1726e800c051794675831c1454ae1e3c73 Mon Sep 17 00:00:00 2001 From: Benoit Daloze Date: Mon, 19 Dec 2022 18:56:30 +0100 Subject: [PATCH] Make Sprockets::Cache::MemoryStore thread-safe by using a Mutex --- lib/sprockets/cache/memory_store.rb | 31 +++++++++++++++++++---------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/lib/sprockets/cache/memory_store.rb b/lib/sprockets/cache/memory_store.rb index 12f5858ca..41a118ed1 100644 --- a/lib/sprockets/cache/memory_store.rb +++ b/lib/sprockets/cache/memory_store.rb @@ -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. @@ -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 @@ -50,9 +53,11 @@ 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 @@ -60,14 +65,18 @@ def set(key, value) # # 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