-
Notifications
You must be signed in to change notification settings - Fork 11.2k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix bug with object_by_id inserts. (#20236)
The previous version of this code was based on a misunderstanding of the Moka Cache API. It assumed that: let entry = cache.entry(k).or_insert_with(|| v); entry.is_fresh() could be used to detect whether there was a race with cache.insert(k, v) In fact this is not the case! Both threads must use `or_insert_with` in order to handle the race correctly. The bug is instantly reproducible with the following code: use moka::sync::Cache; use std::sync::{Arc, Mutex}; fn monotonic_update(cache: Arc<Cache<u64, Arc<Mutex<u64>>>>, key: u64, value: u64) { let entry = cache .entry(key) .or_insert_with(|| Arc::new(Mutex::new(value))); if !entry.is_fresh() { let mut entry = entry.value().lock().unwrap(); // only update if the new value is greater than the current value if value > *entry { *entry = value; } } } fn blind_write(cache: Arc<Cache<u64, Arc<Mutex<u64>>>>, key: u64, value: u64) { cache.insert(key, Arc::new(Mutex::new(value))); } fn main() { for _ in 0..1000 { let cache = Arc::new(Cache::new(1000)); let cache1 = cache.clone(); let cache2 = cache.clone(); let handle1 = std::thread::spawn(move || { monotonic_update(cache1, 1, 1); }); let handle2 = std::thread::spawn(move || { // Correct way to update the value // monotonic_update(cache2, 1, 2); // Incorrect way to update the value blind_write(cache2, 1, 2); }); handle1.join().unwrap(); handle2.join().unwrap(); let entry = cache.get(&1).unwrap(); let value = entry.lock().unwrap(); assert_eq!(*value, 2); } } ## Description Describe the changes or additions included in this PR. ## Test plan How did you test the new or updated feature? --- ## Release notes Check each box that your changes affect. If none of the boxes relate to your changes, release notes aren't required. For each box you select, include information after the relevant heading that describes the impact of your changes that a user might notice and any actions they must take to implement updates. - [ ] Protocol: - [ ] Nodes (Validators and Full nodes): - [ ] Indexer: - [ ] JSON-RPC: - [ ] GraphQL: - [ ] CLI: - [ ] Rust SDK: - [ ] REST API:
- Loading branch information
1 parent
ec6d016
commit 297913c
Showing
2 changed files
with
91 additions
and
59 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters