Skip to content

Commit

Permalink
Merge pull request #174 from instacart/cachefix
Browse files Browse the repository at this point in the history
Fixes `can't add a new key into hash during iteration` error
  • Loading branch information
bleonard authored Sep 27, 2017
2 parents b35c26c + 0f76980 commit 9a441f3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/makara/cache/memory_store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ class MemoryStore

def initialize
@data = {}
@mutex = Mutex.new
end

def read(key)
Expand All @@ -20,7 +21,9 @@ def write(key, value, options = {})
protected

def clean
@data.delete_if{|k,v| v[1] <= Time.now.to_i }
@mutex.synchronize do
@data.delete_if{|k,v| v[1] <= Time.now.to_i }
end
end

end
Expand Down
22 changes: 22 additions & 0 deletions spec/cache_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,28 @@
expect(data).not_to have_key('test')
end

it 'has thread-safety' do
store = Makara::Cache::MemoryStore.new
previous_value = Thread.abort_on_exception

begin
Thread.abort_on_exception = true

workers = 2.times.map do
Thread.new do
100.times do |n|
store.write(n, 'value', expires_in: 0.5)
sleep(0.01)
end
end
end

expect { workers.map(&:join) }.to_not raise_error
ensure
Thread.abort_on_exception = previous_value
end
end

end


Expand Down

0 comments on commit 9a441f3

Please sign in to comment.