Skip to content

Commit

Permalink
Merge pull request #49542 from pjambet/pj/fix-memory-store-race-condi…
Browse files Browse the repository at this point in the history
…tion

MemoryStore: prevent race condition
  • Loading branch information
byroot committed Oct 9, 2023
1 parent eae3672 commit 52c4aef
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 9 deletions.
4 changes: 4 additions & 0 deletions activesupport/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
* Fix MemoryStore to prevent race conditions when incrementing or decrementing.

*Pierre Jambet*

## Rails 7.1.0 (October 05, 2023) ##

* No changes.
Expand Down
20 changes: 11 additions & 9 deletions activesupport/lib/active_support/cache/memory_store.rb
Original file line number Diff line number Diff line change
Expand Up @@ -238,16 +238,18 @@ def modify_value(name, amount, options)
key = normalize_key(name, options)
version = normalize_version(name, options)

entry = read_entry(key, **options)
synchronize do
entry = read_entry(key, **options)

if !entry || entry.expired? || entry.mismatched?(version)
write(name, Integer(amount), options)
amount
else
num = entry.value.to_i + amount
entry = Entry.new(num, expires_at: entry.expires_at, version: entry.version)
write_entry(key, entry)
num
if !entry || entry.expired? || entry.mismatched?(version)
write(name, Integer(amount), options)
amount
else
num = entry.value.to_i + amount
entry = Entry.new(num, expires_at: entry.expires_at, version: entry.version)
write_entry(key, entry)
num
end
end
end
end
Expand Down

0 comments on commit 52c4aef

Please sign in to comment.