Skip to content

Commit b3c69c0

Browse files
committed
Make Sprockets::Cache::MemoryStore thread-safe by using a Mutex
1 parent 2b6b2e7 commit b3c69c0

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

lib/sprockets/cache/memory_store.rb

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ class MemoryStore
2222
def initialize(max_size = DEFAULT_MAX_SIZE)
2323
@max_size = max_size
2424
@cache = {}
25+
@mutex = Mutex.new
2526
end
2627

2728
# Public: Retrieve value from cache.
@@ -32,12 +33,14 @@ def initialize(max_size = DEFAULT_MAX_SIZE)
3233
#
3334
# Returns Object or nil or the value is not set.
3435
def get(key)
35-
exists = true
36-
value = @cache.delete(key) { exists = false }
37-
if exists
38-
@cache[key] = value
39-
else
40-
nil
36+
@mutex.synchronize do
37+
exists = true
38+
value = @cache.delete(key) { exists = false }
39+
if exists
40+
@cache[key] = value
41+
else
42+
nil
43+
end
4144
end
4245
end
4346

@@ -50,24 +53,30 @@ def get(key)
5053
#
5154
# Returns Object value.
5255
def set(key, value)
53-
@cache.delete(key)
54-
@cache[key] = value
55-
@cache.shift if @cache.size > @max_size
56+
@mutex.synchronize do
57+
@cache.delete(key)
58+
@cache[key] = value
59+
@cache.shift if @cache.size > @max_size
60+
end
5661
value
5762
end
5863

5964
# Public: Pretty inspect
6065
#
6166
# Returns String.
6267
def inspect
63-
"#<#{self.class} size=#{@cache.size}/#{@max_size}>"
68+
@mutex.synchronize do
69+
"#<#{self.class} size=#{@cache.size}/#{@max_size}>"
70+
end
6471
end
6572

6673
# Public: Clear the cache
6774
#
6875
# Returns true
6976
def clear(options=nil)
70-
@cache.clear
77+
@mutex.synchronize do
78+
@cache.clear
79+
end
7180
true
7281
end
7382
end

0 commit comments

Comments
 (0)