-
-
Notifications
You must be signed in to change notification settings - Fork 73
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support and_try_compute_if_nobody_else #460
Open
xuehaonan27
wants to merge
2
commits into
moka-rs:main
Choose a base branch
from
xuehaonan27:if-nobody-else
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Conversation
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
It will only evaluate one closure for a certain entry, and other closures will be canceled, returning `CompResult::Unchanged`. Add `ValueInitializer::post_init_for_try_compute_with_if_nobody_else`. Add `Cache::try_compute_if_nobody_else_with_hash_and_fun`. Add `RefKeyEntrySelector::and_try_compute_if_nobody_else`.
Codecov ReportAttention: Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #460 +/- ##
==========================================
- Coverage 94.79% 94.21% -0.58%
==========================================
Files 44 43 -1
Lines 20306 20435 +129
==========================================
+ Hits 19249 19253 +4
- Misses 1057 1182 +125 |
Test code: use std::sync::Arc;
use moka::{
future::Cache,
ops::compute::{CompResult, Op},
};
const N: usize = 100000;
const CONCURRENCY: usize = 100; // concurrent task nums
#[tokio::main]
async fn main() {
/*
Note: the final result should less than `N`.
That's okay because we are testing [`and_try_compute_if_nobody_else`] which should
cancel some computations, rather than testing whether the addition itself is thread-safe
or not.
*/
// Uncomment this line to test computation serialized by cache.
// You can only see
// ReplacedWith(Entry { key: "key1", value: <xxx>, is_fresh: true, is_old_value_replaced: true })
// in stdout, which is as expected.
computation_serialized().await;
// Uncomment this line to test new feature.
// You can see lines like:
// Unchanged(Entry { key: "key1", value: <xxx>, is_fresh: false, is_old_value_replaced: false })
// in stdout, which is as expected because there are multiple waiters manipulating the same
// entry simutaneously.
// However, I am not sure whether [`CompResult`] like `Unchanged` is proper for
// this situation where the computation is cancelled because of another waiter
// occupying the entry.
// Should we add a new Enum to [`CompResult`] to represent this situation?
computation_maybe_cancelled().await;
}
async fn computation_serialized() {
// Increment a cached `u64` counter.
async fn inclement_counter(cache: &Cache<String, u64>, key: &str) -> CompResult<String, u64> {
cache
.entry_by_ref(key)
.and_compute_with(|maybe_entry| {
let op = if let Some(entry) = maybe_entry {
let counter = entry.into_value();
Op::Put(counter.saturating_add(1)) // Update
} else {
Op::Put(1) // Insert
};
// Return a Future that is resolved to `op` immediately.
std::future::ready(op)
})
.await
}
let cache: Arc<Cache<String, u64>> = Arc::new(Cache::new(100));
let key = "key1".to_string();
let mut handles = Vec::new();
for _ in 0..CONCURRENCY {
let cache_clone = Arc::clone(&cache);
let key_clone = key.clone();
let handle = tokio::spawn(async move {
for _ in 0..(N / CONCURRENCY) {
let res = inclement_counter(&cache_clone, &key_clone).await;
println!("{:?}", res);
}
});
handles.push(handle);
}
for handle in handles {
handle.await.unwrap();
}
let result = cache.get(&key).await;
println!("{result:?}");
}
async fn computation_maybe_cancelled() {
// Increment a cached `u64` counter.
async fn inclement_counter_if_nobody_else(
cache: &Cache<String, u64>,
key: &str,
) -> Result<CompResult<String, u64>, ()> {
cache
.entry_by_ref(key)
.and_try_compute_if_nobody_else(|maybe_entry| {
let op = if let Some(entry) = maybe_entry {
let counter = entry.into_value();
Ok(Op::Put(counter.saturating_add(1))) // Update
} else {
Ok(Op::Put(1)) // Insert
};
// Return a Future that is resolved to `op` immediately.
std::future::ready(op)
})
.await
}
let cache: Arc<Cache<String, u64>> = Arc::new(Cache::new(100));
let key = "key1".to_string();
let mut handles = Vec::new();
for _ in 0..CONCURRENCY {
let cache_clone = Arc::clone(&cache);
let key_clone = key.clone();
let handle = tokio::spawn(async move {
for _ in 0..(N / CONCURRENCY) {
let res = inclement_counter_if_nobody_else(&cache_clone, &key_clone)
.await
.unwrap(); // unwrap safe
println!("{:?}", res);
}
});
handles.push(handle);
}
for handle in handles {
handle.await.unwrap();
}
let result = cache.get(&key).await;
println!("{result:?}");
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Issue: #433
It will only evaluate one closure for a certain entry, and other closures will be canceled, returning
CompResult::Unchanged
.Add
ValueInitializer::post_init_for_try_compute_with_if_nobody_else
.Add
Cache::try_compute_if_nobody_else_with_hash_and_fun
.Add
RefKeyEntrySelector::and_try_compute_if_nobody_else
.