moka/sync/cache.rs
1use super::{
2 base_cache::{BaseCache, HouseKeeperArc},
3 value_initializer::{InitResult, ValueInitializer},
4 CacheBuilder, OwnedKeyEntrySelector, RefKeyEntrySelector,
5};
6use crate::{
7 common::{
8 concurrent::{
9 constants::WRITE_RETRY_INTERVAL_MICROS, housekeeper::InnerSync, Weigher, WriteOp,
10 },
11 iter::ScanningGet,
12 time::{Clock, Instant},
13 HousekeeperConfig,
14 },
15 notification::EvictionListener,
16 ops::compute::{self, CompResult},
17 policy::{EvictionPolicy, ExpirationPolicy},
18 sync::{Iter, PredicateId},
19 Entry, Policy, PredicateError,
20};
21
22use crossbeam_channel::{Sender, TrySendError};
23use equivalent::Equivalent;
24use std::{
25 collections::hash_map::RandomState,
26 fmt,
27 hash::{BuildHasher, Hash},
28 sync::Arc,
29 time::Duration,
30};
31
32/// A thread-safe concurrent synchronous in-memory cache.
33///
34/// `Cache` supports full concurrency of retrievals and a high expected concurrency
35/// for updates.
36///
37/// `Cache` utilizes a lock-free concurrent hash table as the central key-value
38/// storage. `Cache` performs a best-effort bounding of the map using an entry
39/// replacement algorithm to determine which entries to evict when the capacity is
40/// exceeded.
41///
42/// # Table of Contents
43///
44/// - [Example: `insert`, `get` and `invalidate`](#example-insert-get-and-invalidate)
45/// - [Avoiding to clone the value at `get`](#avoiding-to-clone-the-value-at-get)
46/// - [Sharing a cache across threads](#sharing-a-cache-across-threads)
47/// - [No lock is needed](#no-lock-is-needed)
48/// - [Hashing Algorithm](#hashing-algorithm)
49/// - [Example: Size-based Eviction](#example-size-based-eviction)
50/// - [Example: Time-based Expirations](#example-time-based-expirations)
51/// - [Cache-level TTL and TTI policies](#cache-level-ttl-and-tti-policies)
52/// - [Per-entry expiration policy](#per-entry-expiration-policy)
53/// - [Example: Eviction Listener](#example-eviction-listener)
54/// - [You should avoid eviction listener to
55/// panic](#you-should-avoid-eviction-listener-to-panic)
56///
57/// # Example: `insert`, `get` and `invalidate`
58///
59/// Cache entries are manually added using [`insert`](#method.insert) or
60/// [`get_with`](#method.get_with) methods, and are stored in the cache until either
61/// evicted or manually invalidated.
62///
63/// Here's an example of reading and updating a cache by using multiple threads:
64///
65/// ```rust
66/// use moka::sync::Cache;
67///
68/// use std::thread;
69///
70/// fn value(n: usize) -> String {
71/// format!("value {n}")
72/// }
73///
74/// const NUM_THREADS: usize = 16;
75/// const NUM_KEYS_PER_THREAD: usize = 64;
76///
77/// // Create a cache that can store up to 10,000 entries.
78/// let cache = Cache::new(10_000);
79///
80/// // Spawn threads and read and update the cache simultaneously.
81/// let threads: Vec<_> = (0..NUM_THREADS)
82/// .map(|i| {
83/// // To share the same cache across the threads, clone it.
84/// // This is a cheap operation.
85/// let my_cache = cache.clone();
86/// let start = i * NUM_KEYS_PER_THREAD;
87/// let end = (i + 1) * NUM_KEYS_PER_THREAD;
88///
89/// thread::spawn(move || {
90/// // Insert 64 entries. (NUM_KEYS_PER_THREAD = 64)
91/// for key in start..end {
92/// my_cache.insert(key, value(key));
93/// // get() returns Option<String>, a clone of the stored value.
94/// assert_eq!(my_cache.get(&key), Some(value(key)));
95/// }
96///
97/// // Invalidate every 4 element of the inserted entries.
98/// for key in (start..end).step_by(4) {
99/// my_cache.invalidate(&key);
100/// }
101/// })
102/// })
103/// .collect();
104///
105/// // Wait for all threads to complete.
106/// threads.into_iter().for_each(|t| t.join().expect("Failed"));
107///
108/// // Verify the result.
109/// for key in 0..(NUM_THREADS * NUM_KEYS_PER_THREAD) {
110/// if key % 4 == 0 {
111/// assert_eq!(cache.get(&key), None);
112/// } else {
113/// assert_eq!(cache.get(&key), Some(value(key)));
114/// }
115/// }
116/// ```
117///
118/// If you want to atomically initialize and insert a value when the key is not
119/// present, you might want to check other insertion methods
120/// [`get_with`](#method.get_with) and [`try_get_with`](#method.try_get_with).
121///
122/// # Avoiding to clone the value at `get`
123///
124/// The return type of `get` method is `Option<V>` instead of `Option<&V>`. Every
125/// time `get` is called for an existing key, it creates a clone of the stored value
126/// `V` and returns it. This is because the `Cache` allows concurrent updates from
127/// threads so a value stored in the cache can be dropped or replaced at any time by
128/// any other thread. `get` cannot return a reference `&V` as it is impossible to
129/// guarantee the value outlives the reference.
130///
131/// If you want to store values that will be expensive to clone, wrap them by
132/// `std::sync::Arc` before storing in a cache. [`Arc`][rustdoc-std-arc] is a
133/// thread-safe reference-counted pointer and its `clone()` method is cheap.
134///
135/// [rustdoc-std-arc]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
136///
137/// # Sharing a cache across threads
138///
139/// To share a cache across threads, do one of the followings:
140///
141/// - Create a clone of the cache by calling its `clone` method and pass it to other
142/// thread.
143/// - Wrap the cache by a `sync::OnceCell` or `sync::Lazy` from
144/// [once_cell][once-cell-crate] create, and set it to a `static` variable.
145///
146/// Cloning is a cheap operation for `Cache` as it only creates thread-safe
147/// reference-counted pointers to the internal data structures.
148///
149/// ## No lock is needed
150///
151/// Don't wrap a `Cache` by a lock such as `Mutex` or `RwLock`. All methods provided
152/// by the `Cache` are considered thread-safe, and can be safely called by multiple
153/// threads at the same time. No lock is needed.
154///
155/// [once-cell-crate]: https://crates.io/crates/once_cell
156///
157/// # Hashing Algorithm
158///
159/// By default, `Cache` uses a hashing algorithm selected to provide resistance
160/// against HashDoS attacks. It will be the same one used by
161/// `std::collections::HashMap`, which is currently SipHash 1-3.
162///
163/// While SipHash's performance is very competitive for medium sized keys, other
164/// hashing algorithms will outperform it for small keys such as integers as well as
165/// large keys such as long strings. However those algorithms will typically not
166/// protect against attacks such as HashDoS.
167///
168/// The hashing algorithm can be replaced on a per-`Cache` basis using the
169/// [`build_with_hasher`][build-with-hasher-method] method of the `CacheBuilder`.
170/// Many alternative algorithms are available on crates.io, such as the
171/// [AHash][ahash-crate] crate.
172///
173/// [build-with-hasher-method]: ./struct.CacheBuilder.html#method.build_with_hasher
174/// [ahash-crate]: https://crates.io/crates/ahash
175///
176/// # Example: Size-based Eviction
177///
178/// ```rust
179/// use moka::sync::Cache;
180///
181/// // Evict based on the number of entries in the cache.
182/// let cache = Cache::builder()
183/// // Up to 10,000 entries.
184/// .max_capacity(10_000)
185/// // Create the cache.
186/// .build();
187/// cache.insert(1, "one".to_string());
188///
189/// // Evict based on the byte length of strings in the cache.
190/// let cache = Cache::builder()
191/// // A weigher closure takes &K and &V and returns a u32
192/// // representing the relative size of the entry.
193/// .weigher(|_key, value: &String| -> u32 {
194/// value.len().try_into().unwrap_or(u32::MAX)
195/// })
196/// // This cache will hold up to 32MiB of values.
197/// .max_capacity(32 * 1024 * 1024)
198/// .build();
199/// cache.insert(2, "two".to_string());
200/// ```
201///
202/// If your cache should not grow beyond a certain size, use the `max_capacity`
203/// method of the [`CacheBuilder`][builder-struct] to set the upper bound. The cache
204/// will try to evict entries that have not been used recently or very often.
205///
206/// At the cache creation time, a weigher closure can be set by the `weigher` method
207/// of the `CacheBuilder`. A weigher closure takes `&K` and `&V` as the arguments and
208/// returns a `u32` representing the relative size of the entry:
209///
210/// - If the `weigher` is _not_ set, the cache will treat each entry has the same
211/// size of `1`. This means the cache will be bounded by the number of entries.
212/// - If the `weigher` is set, the cache will call the weigher to calculate the
213/// weighted size (relative size) on an entry. This means the cache will be bounded
214/// by the total weighted size of entries.
215///
216/// Note that weighted sizes are not used when making eviction selections.
217///
218/// [builder-struct]: ./struct.CacheBuilder.html
219///
220/// # Example: Time-based Expirations
221///
222/// ## Cache-level TTL and TTI policies
223///
224/// `Cache` supports the following cache-level expiration policies:
225///
226/// - **Time to live (TTL)**: A cached entry will be expired after the specified
227/// duration past from `insert`.
228/// - **Time to idle (TTI)**: A cached entry will be expired after the specified
229/// duration past from `get` or `insert`.
230///
231/// They are a cache-level expiration policies; all entries in the cache will have
232/// the same TTL and/or TTI durations. If you want to set different expiration
233/// durations for different entries, see the next section.
234///
235/// ```rust
236/// use moka::sync::Cache;
237/// use std::time::Duration;
238///
239/// let cache = Cache::builder()
240/// // Time to live (TTL): 30 minutes
241/// .time_to_live(Duration::from_secs(30 * 60))
242/// // Time to idle (TTI): 5 minutes
243/// .time_to_idle(Duration::from_secs( 5 * 60))
244/// // Create the cache.
245/// .build();
246///
247/// // This entry will expire after 5 minutes (TTI) if there is no get().
248/// cache.insert(0, "zero");
249///
250/// // This get() will extend the entry life for another 5 minutes.
251/// cache.get(&0);
252///
253/// // Even though we keep calling get(), the entry will expire
254/// // after 30 minutes (TTL) from the insert().
255/// ```
256///
257/// ## Per-entry expiration policy
258///
259/// `Cache` supports per-entry expiration policy through the `Expiry` trait.
260///
261/// `Expiry` trait provides three callback methods:
262/// [`expire_after_create`][exp-create], [`expire_after_read`][exp-read] and
263/// [`expire_after_update`][exp-update]. When a cache entry is inserted, read or
264/// updated, one of these methods is called. These methods return an
265/// `Option<Duration>`, which is used as the expiration duration of the entry.
266///
267/// `Expiry` trait provides the default implementations of these methods, so you will
268/// implement only the methods you want to customize.
269///
270/// [exp-create]: ../trait.Expiry.html#method.expire_after_create
271/// [exp-read]: ../trait.Expiry.html#method.expire_after_read
272/// [exp-update]: ../trait.Expiry.html#method.expire_after_update
273///
274/// ```rust
275/// use moka::{sync::Cache, Expiry};
276/// use std::time::{Duration, Instant};
277///
278/// // In this example, we will create a `sync::Cache` with `u32` as the key, and
279/// // `(Expiration, String)` as the value. `Expiration` is an enum to represent the
280/// // expiration of the value, and `String` is the application data of the value.
281///
282/// /// An enum to represent the expiration of a value.
283/// #[derive(Clone, Copy, Debug, Eq, PartialEq)]
284/// pub enum Expiration {
285/// /// The value never expires.
286/// Never,
287/// /// The value expires after a short time. (5 seconds in this example)
288/// AfterShortTime,
289/// /// The value expires after a long time. (15 seconds in this example)
290/// AfterLongTime,
291/// }
292///
293/// impl Expiration {
294/// /// Returns the duration of this expiration.
295/// pub fn as_duration(&self) -> Option<Duration> {
296/// match self {
297/// Expiration::Never => None,
298/// Expiration::AfterShortTime => Some(Duration::from_secs(5)),
299/// Expiration::AfterLongTime => Some(Duration::from_secs(15)),
300/// }
301/// }
302/// }
303///
304/// /// An expiry that implements `moka::Expiry` trait. `Expiry` trait provides the
305/// /// default implementations of three callback methods `expire_after_create`,
306/// /// `expire_after_read`, and `expire_after_update`.
307/// ///
308/// /// In this example, we only override the `expire_after_create` method.
309/// pub struct MyExpiry;
310///
311/// impl Expiry<u32, (Expiration, String)> for MyExpiry {
312/// /// Returns the duration of the expiration of the value that was just
313/// /// created.
314/// fn expire_after_create(
315/// &self,
316/// _key: &u32,
317/// value: &(Expiration, String),
318/// _current_time: Instant,
319/// ) -> Option<Duration> {
320/// let duration = value.0.as_duration();
321/// println!("MyExpiry: expire_after_create called with key {_key} and value {value:?}. Returning {duration:?}.");
322/// duration
323/// }
324/// }
325///
326/// // Create a `Cache<u32, (Expiration, String)>` with an expiry `MyExpiry` and
327/// // eviction listener.
328/// let expiry = MyExpiry;
329///
330/// let eviction_listener = |key, _value, cause| {
331/// println!("Evicted key {key}. Cause: {cause:?}");
332/// };
333///
334/// let cache = Cache::builder()
335/// .max_capacity(100)
336/// .expire_after(expiry)
337/// .eviction_listener(eviction_listener)
338/// .build();
339///
340/// // Insert some entries into the cache with different expirations.
341/// cache.get_with(0, || (Expiration::AfterShortTime, "a".to_string()));
342/// cache.get_with(1, || (Expiration::AfterLongTime, "b".to_string()));
343/// cache.get_with(2, || (Expiration::Never, "c".to_string()));
344///
345/// // Verify that all the inserted entries exist.
346/// assert!(cache.contains_key(&0));
347/// assert!(cache.contains_key(&1));
348/// assert!(cache.contains_key(&2));
349///
350/// // Sleep for 6 seconds. Key 0 should expire.
351/// println!("\nSleeping for 6 seconds...\n");
352/// std::thread::sleep(Duration::from_secs(6));
353/// println!("Entry count: {}", cache.entry_count());
354///
355/// // Verify that key 0 has been evicted.
356/// assert!(!cache.contains_key(&0));
357/// assert!(cache.contains_key(&1));
358/// assert!(cache.contains_key(&2));
359///
360/// // Sleep for 10 more seconds. Key 1 should expire.
361/// println!("\nSleeping for 10 seconds...\n");
362/// std::thread::sleep(Duration::from_secs(10));
363/// println!("Entry count: {}", cache.entry_count());
364///
365/// // Verify that key 1 has been evicted.
366/// assert!(!cache.contains_key(&1));
367/// assert!(cache.contains_key(&2));
368///
369/// // Manually invalidate key 2.
370/// cache.invalidate(&2);
371/// assert!(!cache.contains_key(&2));
372///
373/// println!("\nSleeping for a second...\n");
374/// std::thread::sleep(Duration::from_secs(1));
375/// println!("Entry count: {}", cache.entry_count());
376///
377/// println!("\nDone!");
378/// ```
379///
380/// # Example: Eviction Listener
381///
382/// A `Cache` can be configured with an eviction listener, a closure that is called
383/// every time there is a cache eviction. The listener takes three parameters: the
384/// key and value of the evicted entry, and the
385/// [`RemovalCause`](../notification/enum.RemovalCause.html) to indicate why the
386/// entry was evicted.
387///
388/// An eviction listener can be used to keep other data structures in sync with the
389/// cache, for example.
390///
391/// The following example demonstrates how to use an eviction listener with
392/// time-to-live expiration to manage the lifecycle of temporary files on a
393/// filesystem. The cache stores the paths of the files, and when one of them has
394/// expired, the eviction listener will be called with the path, so it can remove the
395/// file from the filesystem.
396///
397/// ```rust
398/// // Cargo.toml
399/// //
400/// // [dependencies]
401/// // anyhow = "1.0"
402/// // uuid = { version = "1.1", features = ["v4"] }
403///
404/// use moka::{sync::Cache, notification};
405///
406/// use anyhow::{anyhow, Context};
407/// use std::{
408/// fs, io,
409/// path::{Path, PathBuf},
410/// sync::{Arc, RwLock},
411/// time::Duration,
412/// };
413/// use uuid::Uuid;
414///
415/// /// The DataFileManager writes, reads and removes data files.
416/// struct DataFileManager {
417/// base_dir: PathBuf,
418/// file_count: usize,
419/// }
420///
421/// impl DataFileManager {
422/// fn new(base_dir: PathBuf) -> Self {
423/// Self {
424/// base_dir,
425/// file_count: 0,
426/// }
427/// }
428///
429/// fn write_data_file(
430/// &mut self,
431/// key: impl AsRef<str>,
432/// contents: String
433/// ) -> io::Result<PathBuf> {
434/// // Use the key as a part of the filename.
435/// let mut path = self.base_dir.to_path_buf();
436/// path.push(key.as_ref());
437///
438/// assert!(!path.exists(), "Path already exists: {path:?}");
439///
440/// // create the file at the path and write the contents to the file.
441/// fs::write(&path, contents)?;
442/// self.file_count += 1;
443/// println!("Created a data file at {path:?} (file count: {})", self.file_count);
444/// Ok(path)
445/// }
446///
447/// fn read_data_file(&self, path: impl AsRef<Path>) -> io::Result<String> {
448/// // Reads the contents of the file at the path, and return the contents.
449/// fs::read_to_string(path)
450/// }
451///
452/// fn remove_data_file(&mut self, path: impl AsRef<Path>) -> io::Result<()> {
453/// // Remove the file at the path.
454/// fs::remove_file(path.as_ref())?;
455/// self.file_count -= 1;
456/// println!(
457/// "Removed a data file at {:?} (file count: {})",
458/// path.as_ref(),
459/// self.file_count
460/// );
461///
462/// Ok(())
463/// }
464/// }
465///
466/// fn main() -> anyhow::Result<()> {
467/// // Create an instance of the DataFileManager and wrap it with
468/// // Arc<RwLock<_>> so it can be shared across threads.
469/// let mut base_dir = std::env::temp_dir();
470/// base_dir.push(Uuid::new_v4().as_hyphenated().to_string());
471/// println!("base_dir: {base_dir:?}");
472/// std::fs::create_dir(&base_dir)?;
473///
474/// let file_mgr = DataFileManager::new(base_dir);
475/// let file_mgr = Arc::new(RwLock::new(file_mgr));
476///
477/// let file_mgr1 = Arc::clone(&file_mgr);
478///
479/// // Create an eviction listener closure.
480/// let eviction_listener = move |k, v: PathBuf, cause| {
481/// // Try to remove the data file at the path `v`.
482/// println!("\n== An entry has been evicted. k: {k:?}, v: {v:?}, cause: {cause:?}");
483///
484/// // Acquire the write lock of the DataFileManager. We must handle
485/// // error cases here to prevent the listener from panicking.
486/// match file_mgr1.write() {
487/// Err(_e) => {
488/// eprintln!("The lock has been poisoned");
489/// }
490/// Ok(mut mgr) => {
491/// // Remove the data file using the DataFileManager.
492/// if let Err(_e) = mgr.remove_data_file(v.as_path()) {
493/// eprintln!("Failed to remove a data file at {v:?}");
494/// }
495/// }
496/// }
497/// };
498///
499/// // Create the cache. Set time to live for two seconds and set the
500/// // eviction listener.
501/// let cache = Cache::builder()
502/// .max_capacity(100)
503/// .time_to_live(Duration::from_secs(2))
504/// .eviction_listener(eviction_listener)
505/// .build();
506///
507/// // Insert an entry to the cache.
508/// // This will create and write a data file for the key "user1", store the
509/// // path of the file to the cache, and return it.
510/// println!("== try_get_with()");
511/// let key = "user1";
512/// let path = cache
513/// .try_get_with(key, || -> anyhow::Result<_> {
514/// let mut mgr = file_mgr
515/// .write()
516/// .map_err(|_e| anyhow::anyhow!("The lock has been poisoned"))?;
517/// let path = mgr
518/// .write_data_file(key, "user data".into())
519/// .with_context(|| format!("Failed to create a data file"))?;
520/// Ok(path)
521/// })
522/// .map_err(|e| anyhow!("{e}"))?;
523///
524/// // Read the data file at the path and print the contents.
525/// println!("\n== read_data_file()");
526/// {
527/// let mgr = file_mgr
528/// .read()
529/// .map_err(|_e| anyhow::anyhow!("The lock has been poisoned"))?;
530/// let contents = mgr
531/// .read_data_file(path.as_path())
532/// .with_context(|| format!("Failed to read data from {path:?}"))?;
533/// println!("contents: {contents}");
534/// }
535///
536/// // Sleep for five seconds. While sleeping, the cache entry for key "user1"
537/// // will be expired and evicted, so the eviction listener will be called to
538/// // remove the file.
539/// std::thread::sleep(Duration::from_secs(5));
540///
541/// cache.run_pending_tasks();
542///
543/// Ok(())
544/// }
545/// ```
546///
547/// ## You should avoid eviction listener to panic
548///
549/// It is very important to make an eviction listener closure not to panic.
550/// Otherwise, the cache will stop calling the listener after a panic. This is an
551/// intended behavior because the cache cannot know whether it is memory safe or not
552/// to call the panicked listener again.
553///
554/// When a listener panics, the cache will swallow the panic and disable the
555/// listener. If you want to know when a listener panics and the reason of the panic,
556/// you can enable an optional `logging` feature of Moka and check error-level logs.
557///
558/// To enable the `logging`, do the followings:
559///
560/// 1. In `Cargo.toml`, add the crate feature `logging` for `moka`.
561/// 2. Set the logging level for `moka` to `error` or any lower levels (`warn`,
562/// `info`, ...):
563/// - If you are using the `env_logger` crate, you can achieve this by setting
564/// `RUST_LOG` environment variable to `moka=error`.
565/// 3. If you have more than one caches, you may want to set a distinct name for each
566/// cache by using cache builder's [`name`][builder-name-method] method. The name
567/// will appear in the log.
568///
569/// [builder-name-method]: ./struct.CacheBuilder.html#method.name
570///
571pub struct Cache<K, V, S = RandomState> {
572 pub(crate) base: BaseCache<K, V, S>,
573 value_initializer: Arc<ValueInitializer<K, V, S>>,
574}
575
576unsafe impl<K, V, S> Send for Cache<K, V, S>
577where
578 K: Send + Sync,
579 V: Send + Sync,
580 S: Send,
581{
582}
583
584unsafe impl<K, V, S> Sync for Cache<K, V, S>
585where
586 K: Send + Sync,
587 V: Send + Sync,
588 S: Sync,
589{
590}
591
592// NOTE: We cannot do `#[derive(Clone)]` because it will add `Clone` bound to `K`.
593impl<K, V, S> Clone for Cache<K, V, S> {
594 /// Makes a clone of this shared cache.
595 ///
596 /// This operation is cheap as it only creates thread-safe reference counted
597 /// pointers to the shared internal data structures.
598 fn clone(&self) -> Self {
599 Self {
600 base: self.base.clone(),
601 value_initializer: Arc::clone(&self.value_initializer),
602 }
603 }
604}
605
606impl<K, V, S> fmt::Debug for Cache<K, V, S>
607where
608 K: fmt::Debug + Eq + Hash + Send + Sync + 'static,
609 V: fmt::Debug + Clone + Send + Sync + 'static,
610 // TODO: Remove these bounds from S.
611 S: BuildHasher + Clone + Send + Sync + 'static,
612{
613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
614 let mut d_map = f.debug_map();
615
616 for (k, v) in self {
617 d_map.entry(&k, &v);
618 }
619
620 d_map.finish()
621 }
622}
623
624impl<K, V, S> Cache<K, V, S> {
625 /// Returns cache’s name.
626 pub fn name(&self) -> Option<&str> {
627 self.base.name()
628 }
629
630 /// Returns a read-only cache policy of this cache.
631 ///
632 /// At this time, cache policy cannot be modified after cache creation.
633 /// A future version may support to modify it.
634 pub fn policy(&self) -> Policy {
635 self.base.policy()
636 }
637
638 /// Returns an approximate number of entries in this cache.
639 ///
640 /// The value returned is _an estimate_; the actual count may differ if there are
641 /// concurrent insertions or removals, or if some entries are pending removal due
642 /// to expiration. This inaccuracy can be mitigated by performing a
643 /// `run_pending_tasks` first.
644 ///
645 /// # Example
646 ///
647 /// ```rust
648 /// use moka::sync::Cache;
649 ///
650 /// let cache = Cache::new(10);
651 /// cache.insert('n', "Netherland Dwarf");
652 /// cache.insert('l', "Lop Eared");
653 /// cache.insert('d', "Dutch");
654 ///
655 /// // Ensure an entry exists.
656 /// assert!(cache.contains_key(&'n'));
657 ///
658 /// // However, followings may print stale number zeros instead of threes.
659 /// println!("{}", cache.entry_count()); // -> 0
660 /// println!("{}", cache.weighted_size()); // -> 0
661 ///
662 /// // To mitigate the inaccuracy, Call `run_pending_tasks` method to run
663 /// // pending internal tasks.
664 /// cache.run_pending_tasks();
665 ///
666 /// // Followings will print the actual numbers.
667 /// println!("{}", cache.entry_count()); // -> 3
668 /// println!("{}", cache.weighted_size()); // -> 3
669 /// ```
670 ///
671 pub fn entry_count(&self) -> u64 {
672 self.base.entry_count()
673 }
674
675 /// Returns an approximate total weighted size of entries in this cache.
676 ///
677 /// The value returned is _an estimate_; the actual size may differ if there are
678 /// concurrent insertions or removals, or if some entries are pending removal due
679 /// to expiration. This inaccuracy can be mitigated by performing a
680 /// `run_pending_tasks` first. See [`entry_count`](#method.entry_count) for a
681 /// sample code.
682 pub fn weighted_size(&self) -> u64 {
683 self.base.weighted_size()
684 }
685}
686
687impl<K, V> Cache<K, V, RandomState>
688where
689 K: Hash + Eq + Send + Sync + 'static,
690 V: Clone + Send + Sync + 'static,
691{
692 /// Constructs a new `Cache<K, V>` that will store up to the `max_capacity`.
693 ///
694 /// To adjust various configuration knobs such as `initial_capacity` or
695 /// `time_to_live`, use the [`CacheBuilder`][builder-struct].
696 ///
697 /// [builder-struct]: ./struct.CacheBuilder.html
698 pub fn new(max_capacity: u64) -> Self {
699 let build_hasher = RandomState::default();
700 Self::with_everything(
701 None,
702 Some(max_capacity),
703 None,
704 build_hasher,
705 None,
706 EvictionPolicy::default(),
707 None,
708 ExpirationPolicy::default(),
709 HousekeeperConfig::default(),
710 false,
711 Clock::default(),
712 )
713 }
714
715 /// Returns a [`CacheBuilder`][builder-struct], which can builds a `Cache` or
716 /// `SegmentedCache` with various configuration knobs.
717 ///
718 /// [builder-struct]: ./struct.CacheBuilder.html
719 pub fn builder() -> CacheBuilder<K, V, Cache<K, V, RandomState>> {
720 CacheBuilder::default()
721 }
722}
723
724impl<K, V, S> Cache<K, V, S>
725where
726 K: Hash + Eq + Send + Sync + 'static,
727 V: Clone + Send + Sync + 'static,
728 S: BuildHasher + Clone + Send + Sync + 'static,
729{
730 // https://rust-lang.github.io/rust-clippy/master/index.html#too_many_arguments
731 #[allow(clippy::too_many_arguments)]
732 pub(crate) fn with_everything(
733 name: Option<String>,
734 max_capacity: Option<u64>,
735 initial_capacity: Option<usize>,
736 build_hasher: S,
737 weigher: Option<Weigher<K, V>>,
738 eviction_policy: EvictionPolicy,
739 eviction_listener: Option<EvictionListener<K, V>>,
740 expiration_policy: ExpirationPolicy<K, V>,
741 housekeeper_config: HousekeeperConfig,
742 invalidator_enabled: bool,
743 clock: Clock,
744 ) -> Self {
745 Self {
746 base: BaseCache::new(
747 name,
748 max_capacity,
749 initial_capacity,
750 build_hasher.clone(),
751 weigher,
752 eviction_policy,
753 eviction_listener,
754 expiration_policy,
755 housekeeper_config,
756 invalidator_enabled,
757 clock,
758 ),
759 value_initializer: Arc::new(ValueInitializer::with_hasher(build_hasher)),
760 }
761 }
762
763 /// Returns `true` if the cache contains a value for the key.
764 ///
765 /// Unlike the `get` method, this method is not considered a cache read operation,
766 /// so it does not update the historic popularity estimator or reset the idle
767 /// timer for the key.
768 ///
769 /// The key may be any borrowed form of the cache's key type, but `Hash` and `Eq`
770 /// on the borrowed form _must_ match those for the key type.
771 pub fn contains_key<Q>(&self, key: &Q) -> bool
772 where
773 Q: Equivalent<K> + Hash + ?Sized,
774 {
775 self.base.contains_key_with_hash(key, self.base.hash(key))
776 }
777
778 pub(crate) fn contains_key_with_hash<Q>(&self, key: &Q, hash: u64) -> bool
779 where
780 Q: Equivalent<K> + Hash + ?Sized,
781 {
782 self.base.contains_key_with_hash(key, hash)
783 }
784
785 /// Returns a _clone_ of the value corresponding to the key.
786 ///
787 /// If you want to store values that will be expensive to clone, wrap them by
788 /// `std::sync::Arc` before storing in a cache. [`Arc`][rustdoc-std-arc] is a
789 /// thread-safe reference-counted pointer and its `clone()` method is cheap.
790 ///
791 /// The key may be any borrowed form of the cache's key type, but `Hash` and `Eq`
792 /// on the borrowed form _must_ match those for the key type.
793 ///
794 /// [rustdoc-std-arc]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
795 pub fn get<Q>(&self, key: &Q) -> Option<V>
796 where
797 Q: Equivalent<K> + Hash + ?Sized,
798 {
799 self.base
800 .get_with_hash(key, self.base.hash(key), false)
801 .map(Entry::into_value)
802 }
803
804 pub(crate) fn get_with_hash<Q>(&self, key: &Q, hash: u64, need_key: bool) -> Option<Entry<K, V>>
805 where
806 Q: Equivalent<K> + Hash + ?Sized,
807 {
808 self.base.get_with_hash(key, hash, need_key)
809 }
810
811 /// Takes a key `K` and returns an [`OwnedKeyEntrySelector`] that can be used to
812 /// select or insert an entry.
813 ///
814 /// [`OwnedKeyEntrySelector`]: ./struct.OwnedKeyEntrySelector.html
815 ///
816 /// # Example
817 ///
818 /// ```rust
819 /// use moka::sync::Cache;
820 ///
821 /// let cache: Cache<String, u32> = Cache::new(100);
822 /// let key = "key1".to_string();
823 ///
824 /// let entry = cache.entry(key.clone()).or_insert(3);
825 /// assert!(entry.is_fresh());
826 /// assert_eq!(entry.key(), &key);
827 /// assert_eq!(entry.into_value(), 3);
828 ///
829 /// let entry = cache.entry(key).or_insert(6);
830 /// // Not fresh because the value was already in the cache.
831 /// assert!(!entry.is_fresh());
832 /// assert_eq!(entry.into_value(), 3);
833 /// ```
834 pub fn entry(&self, key: K) -> OwnedKeyEntrySelector<'_, K, V, S>
835 where
836 K: Hash + Eq,
837 {
838 let hash = self.base.hash(&key);
839 OwnedKeyEntrySelector::new(key, hash, self)
840 }
841
842 /// Takes a reference `&Q` of a key and returns an [`RefKeyEntrySelector`] that
843 /// can be used to select or insert an entry.
844 ///
845 /// [`RefKeyEntrySelector`]: ./struct.RefKeyEntrySelector.html
846 ///
847 /// # Example
848 ///
849 /// ```rust
850 /// use moka::sync::Cache;
851 ///
852 /// let cache: Cache<String, u32> = Cache::new(100);
853 /// let key = "key1".to_string();
854 ///
855 /// let entry = cache.entry_by_ref(&key).or_insert(3);
856 /// assert!(entry.is_fresh());
857 /// assert_eq!(entry.key(), &key);
858 /// assert_eq!(entry.into_value(), 3);
859 ///
860 /// let entry = cache.entry_by_ref(&key).or_insert(6);
861 /// // Not fresh because the value was already in the cache.
862 /// assert!(!entry.is_fresh());
863 /// assert_eq!(entry.into_value(), 3);
864 /// ```
865 pub fn entry_by_ref<'a, Q>(&'a self, key: &'a Q) -> RefKeyEntrySelector<'a, K, Q, V, S>
866 where
867 Q: Equivalent<K> + ToOwned<Owned = K> + Hash + ?Sized,
868 {
869 let hash = self.base.hash(key);
870 RefKeyEntrySelector::new(key, hash, self)
871 }
872
873 /// Returns a _clone_ of the value corresponding to the key. If the value does
874 /// not exist, evaluates the `init` closure and inserts the output.
875 ///
876 /// # Concurrent calls on the same key
877 ///
878 /// This method guarantees that concurrent calls on the same not-existing key are
879 /// coalesced into one evaluation of the `init` closure. Only one of the calls
880 /// evaluates its closure, and other calls wait for that closure to complete.
881 ///
882 /// The following code snippet demonstrates this behavior:
883 ///
884 /// ```rust
885 /// use moka::sync::Cache;
886 /// use std::{sync::Arc, thread};
887 ///
888 /// const TEN_MIB: usize = 10 * 1024 * 1024; // 10MiB
889 /// let cache = Cache::new(100);
890 ///
891 /// // Spawn four threads.
892 /// let threads: Vec<_> = (0..4_u8)
893 /// .map(|task_id| {
894 /// let my_cache = cache.clone();
895 /// thread::spawn(move || {
896 /// println!("Thread {task_id} started.");
897 ///
898 /// // Try to insert and get the value for key1. Although all four
899 /// // threads will call `get_with` at the same time, the `init` closure
900 /// // must be evaluated only once.
901 /// let value = my_cache.get_with("key1", || {
902 /// println!("Thread {task_id} inserting a value.");
903 /// Arc::new(vec![0u8; TEN_MIB])
904 /// });
905 ///
906 /// // Ensure the value exists now.
907 /// assert_eq!(value.len(), TEN_MIB);
908 /// assert!(my_cache.get(&"key1").is_some());
909 ///
910 /// println!("Thread {task_id} got the value. (len: {})", value.len());
911 /// })
912 /// })
913 /// .collect();
914 ///
915 /// // Wait all threads to complete.
916 /// threads
917 /// .into_iter()
918 /// .for_each(|t| t.join().expect("Thread failed"));
919 /// ```
920 ///
921 /// **Result**
922 ///
923 /// - The `init` closure was called exactly once by thread 1.
924 /// - Other threads were blocked until thread 1 inserted the value.
925 ///
926 /// ```console
927 /// Thread 1 started.
928 /// Thread 0 started.
929 /// Thread 3 started.
930 /// Thread 2 started.
931 /// Thread 1 inserting a value.
932 /// Thread 2 got the value. (len: 10485760)
933 /// Thread 1 got the value. (len: 10485760)
934 /// Thread 0 got the value. (len: 10485760)
935 /// Thread 3 got the value. (len: 10485760)
936 /// ```
937 ///
938 /// # Panics
939 ///
940 /// This method panics when the `init` closure has panicked. When it happens,
941 /// only the caller whose `init` closure panicked will get the panic (e.g. only
942 /// thread 1 in the above sample). If there are other calls in progress (e.g.
943 /// thread 0, 2 and 3 above), this method will restart and resolve one of the
944 /// remaining `init` closure.
945 ///
946 pub fn get_with(&self, key: K, init: impl FnOnce() -> V) -> V {
947 let hash = self.base.hash(&key);
948 let key = Arc::new(key);
949 let replace_if = None as Option<fn(&V) -> bool>;
950 self.get_or_insert_with_hash_and_fun(key, hash, init, replace_if, false)
951 .into_value()
952 }
953
954 /// Similar to [`get_with`](#method.get_with), but instead of passing an owned
955 /// key, you can pass a reference to the key. If the key does not exist in the
956 /// cache, the key will be cloned to create new entry in the cache.
957 pub fn get_with_by_ref<Q>(&self, key: &Q, init: impl FnOnce() -> V) -> V
958 where
959 Q: Equivalent<K> + ToOwned<Owned = K> + Hash + ?Sized,
960 {
961 let hash = self.base.hash(key);
962 let replace_if = None as Option<fn(&V) -> bool>;
963
964 self.get_or_insert_with_hash_by_ref_and_fun(key, hash, init, replace_if, false)
965 .into_value()
966 }
967
968 /// TODO: Remove this in v0.13.0.
969 /// Deprecated, replaced with
970 /// [`entry()::or_insert_with_if()`](./struct.OwnedKeyEntrySelector.html#method.or_insert_with_if)
971 #[deprecated(since = "0.10.0", note = "Replaced with `entry().or_insert_with_if()`")]
972 pub fn get_with_if(
973 &self,
974 key: K,
975 init: impl FnOnce() -> V,
976 replace_if: impl FnMut(&V) -> bool,
977 ) -> V {
978 let hash = self.base.hash(&key);
979 let key = Arc::new(key);
980 self.get_or_insert_with_hash_and_fun(key, hash, init, Some(replace_if), false)
981 .into_value()
982 }
983
984 pub(crate) fn get_or_insert_with_hash_and_fun(
985 &self,
986 key: Arc<K>,
987 hash: u64,
988 init: impl FnOnce() -> V,
989 mut replace_if: Option<impl FnMut(&V) -> bool>,
990 need_key: bool,
991 ) -> Entry<K, V> {
992 self.base
993 .get_with_hash_and_ignore_if(&*key, hash, replace_if.as_mut(), need_key)
994 .unwrap_or_else(|| self.insert_with_hash_and_fun(key, hash, init, replace_if, need_key))
995 }
996
997 // Need to create new function instead of using the existing
998 // `get_or_insert_with_hash_and_fun`. The reason is `by_ref` function will
999 // require key reference to have `ToOwned` trait. If we modify the existing
1000 // `get_or_insert_with_hash_and_fun` function, it will require all the existing
1001 // apis that depends on it to make the `K` to have `ToOwned` trait.
1002 pub(crate) fn get_or_insert_with_hash_by_ref_and_fun<Q>(
1003 &self,
1004 key: &Q,
1005 hash: u64,
1006 init: impl FnOnce() -> V,
1007 mut replace_if: Option<impl FnMut(&V) -> bool>,
1008 need_key: bool,
1009 ) -> Entry<K, V>
1010 where
1011 Q: Equivalent<K> + ToOwned<Owned = K> + Hash + ?Sized,
1012 {
1013 self.base
1014 .get_with_hash_and_ignore_if(key, hash, replace_if.as_mut(), need_key)
1015 .unwrap_or_else(|| {
1016 let key = Arc::new(key.to_owned());
1017 self.insert_with_hash_and_fun(key, hash, init, replace_if, need_key)
1018 })
1019 }
1020
1021 pub(crate) fn insert_with_hash_and_fun(
1022 &self,
1023 key: Arc<K>,
1024 hash: u64,
1025 init: impl FnOnce() -> V,
1026 mut replace_if: Option<impl FnMut(&V) -> bool>,
1027 need_key: bool,
1028 ) -> Entry<K, V> {
1029 let get = || {
1030 self.base
1031 .get_with_hash_without_recording(&*key, hash, replace_if.as_mut())
1032 };
1033 let insert = |v| self.insert_with_hash(key.clone(), hash, v);
1034
1035 let k = if need_key {
1036 Some(Arc::clone(&key))
1037 } else {
1038 None
1039 };
1040
1041 let type_id = ValueInitializer::<K, V, S>::type_id_for_get_with();
1042 let post_init = ValueInitializer::<K, V, S>::post_init_for_get_with;
1043
1044 match self
1045 .value_initializer
1046 .try_init_or_read(&key, type_id, get, init, insert, post_init)
1047 {
1048 InitResult::Initialized(v) => {
1049 crossbeam_epoch::pin().flush();
1050 Entry::new(k, v, true, false)
1051 }
1052 InitResult::ReadExisting(v) => Entry::new(k, v, false, false),
1053 InitResult::InitErr(_) => unreachable!(),
1054 }
1055 }
1056
1057 pub(crate) fn get_or_insert_with_hash(
1058 &self,
1059 key: Arc<K>,
1060 hash: u64,
1061 init: impl FnOnce() -> V,
1062 ) -> Entry<K, V> {
1063 match self.base.get_with_hash(&*key, hash, true) {
1064 Some(entry) => entry,
1065 None => {
1066 let value = init();
1067 self.insert_with_hash(Arc::clone(&key), hash, value.clone());
1068 Entry::new(Some(key), value, true, false)
1069 }
1070 }
1071 }
1072
1073 pub(crate) fn get_or_insert_with_hash_by_ref<Q>(
1074 &self,
1075 key: &Q,
1076 hash: u64,
1077 init: impl FnOnce() -> V,
1078 ) -> Entry<K, V>
1079 where
1080 Q: Equivalent<K> + ToOwned<Owned = K> + Hash + ?Sized,
1081 {
1082 match self.base.get_with_hash(key, hash, true) {
1083 Some(entry) => entry,
1084 None => {
1085 let key = Arc::new(key.to_owned());
1086 let value = init();
1087 self.insert_with_hash(Arc::clone(&key), hash, value.clone());
1088 Entry::new(Some(key), value, true, false)
1089 }
1090 }
1091 }
1092
1093 /// Returns a _clone_ of the value corresponding to the key. If the value does
1094 /// not exist, evaluates the `init` closure, and inserts the value if
1095 /// `Some(value)` was returned. If `None` was returned from the closure, this
1096 /// method does not insert a value and returns `None`.
1097 ///
1098 /// # Concurrent calls on the same key
1099 ///
1100 /// This method guarantees that concurrent calls on the same not-existing key are
1101 /// coalesced into one evaluation of the `init` closure. Only one of the calls
1102 /// evaluates its closure, and other calls wait for that closure to complete.
1103 ///
1104 /// The following code snippet demonstrates this behavior:
1105 ///
1106 /// ```rust
1107 /// use moka::sync::Cache;
1108 /// use std::{path::Path, thread};
1109 ///
1110 /// /// This function tries to get the file size in bytes.
1111 /// fn get_file_size(thread_id: u8, path: impl AsRef<Path>) -> Option<u64> {
1112 /// println!("get_file_size() called by thread {thread_id}.");
1113 /// std::fs::metadata(path).ok().map(|m| m.len())
1114 /// }
1115 ///
1116 /// let cache = Cache::new(100);
1117 ///
1118 /// // Spawn four threads.
1119 /// let threads: Vec<_> = (0..4_u8)
1120 /// .map(|thread_id| {
1121 /// let my_cache = cache.clone();
1122 /// thread::spawn(move || {
1123 /// println!("Thread {thread_id} started.");
1124 ///
1125 /// // Try to insert and get the value for key1. Although all four
1126 /// // threads will call `optionally_get_with` at the same time,
1127 /// // get_file_size() must be called only once.
1128 /// let value = my_cache.optionally_get_with(
1129 /// "key1",
1130 /// || get_file_size(thread_id, "./Cargo.toml"),
1131 /// );
1132 ///
1133 /// // Ensure the value exists now.
1134 /// assert!(value.is_some());
1135 /// assert!(my_cache.get(&"key1").is_some());
1136 ///
1137 /// println!(
1138 /// "Thread {thread_id} got the value. (len: {})",
1139 /// value.unwrap()
1140 /// );
1141 /// })
1142 /// })
1143 /// .collect();
1144 ///
1145 /// // Wait all threads to complete.
1146 /// threads
1147 /// .into_iter()
1148 /// .for_each(|t| t.join().expect("Thread failed"));
1149 /// ```
1150 ///
1151 /// **Result**
1152 ///
1153 /// - `get_file_size()` was called exactly once by thread 0.
1154 /// - Other threads were blocked until thread 0 inserted the value.
1155 ///
1156 /// ```console
1157 /// Thread 0 started.
1158 /// Thread 1 started.
1159 /// Thread 2 started.
1160 /// get_file_size() called by thread 0.
1161 /// Thread 3 started.
1162 /// Thread 2 got the value. (len: 1466)
1163 /// Thread 0 got the value. (len: 1466)
1164 /// Thread 1 got the value. (len: 1466)
1165 /// Thread 3 got the value. (len: 1466)
1166 /// ```
1167 ///
1168 /// # Panics
1169 ///
1170 /// This method panics when the `init` closure has panicked. When it happens,
1171 /// only the caller whose `init` closure panicked will get the panic (e.g. only
1172 /// thread 1 in the above sample). If there are other calls in progress (e.g.
1173 /// thread 0, 2 and 3 above), this method will restart and resolve one of the
1174 /// remaining `init` closure.
1175 ///
1176 pub fn optionally_get_with<F>(&self, key: K, init: F) -> Option<V>
1177 where
1178 F: FnOnce() -> Option<V>,
1179 {
1180 let hash = self.base.hash(&key);
1181 let key = Arc::new(key);
1182
1183 self.get_or_optionally_insert_with_hash_and_fun(key, hash, init, false)
1184 .map(Entry::into_value)
1185 }
1186
1187 /// Similar to [`optionally_get_with`](#method.optionally_get_with), but instead
1188 /// of passing an owned key, you can pass a reference to the key. If the key does
1189 /// not exist in the cache, the key will be cloned to create new entry in the
1190 /// cache.
1191 pub fn optionally_get_with_by_ref<F, Q>(&self, key: &Q, init: F) -> Option<V>
1192 where
1193 F: FnOnce() -> Option<V>,
1194 Q: Equivalent<K> + ToOwned<Owned = K> + Hash + ?Sized,
1195 {
1196 let hash = self.base.hash(key);
1197 self.get_or_optionally_insert_with_hash_by_ref_and_fun(key, hash, init, false)
1198 .map(Entry::into_value)
1199 }
1200
1201 pub(super) fn get_or_optionally_insert_with_hash_and_fun<F>(
1202 &self,
1203 key: Arc<K>,
1204 hash: u64,
1205 init: F,
1206 need_key: bool,
1207 ) -> Option<Entry<K, V>>
1208 where
1209 F: FnOnce() -> Option<V>,
1210 {
1211 let entry = self.get_with_hash(&*key, hash, need_key);
1212 if entry.is_some() {
1213 return entry;
1214 }
1215
1216 self.optionally_insert_with_hash_and_fun(key, hash, init, need_key)
1217 }
1218
1219 pub(super) fn get_or_optionally_insert_with_hash_by_ref_and_fun<F, Q>(
1220 &self,
1221 key: &Q,
1222 hash: u64,
1223 init: F,
1224 need_key: bool,
1225 ) -> Option<Entry<K, V>>
1226 where
1227 F: FnOnce() -> Option<V>,
1228 Q: Equivalent<K> + ToOwned<Owned = K> + Hash + ?Sized,
1229 {
1230 let entry = self.get_with_hash(key, hash, need_key);
1231 if entry.is_some() {
1232 return entry;
1233 }
1234
1235 let key = Arc::new(key.to_owned());
1236 self.optionally_insert_with_hash_and_fun(key, hash, init, need_key)
1237 }
1238
1239 pub(super) fn optionally_insert_with_hash_and_fun<F>(
1240 &self,
1241 key: Arc<K>,
1242 hash: u64,
1243 init: F,
1244 need_key: bool,
1245 ) -> Option<Entry<K, V>>
1246 where
1247 F: FnOnce() -> Option<V>,
1248 {
1249 let get = || {
1250 let ignore_if = None as Option<&mut fn(&V) -> bool>;
1251 self.base
1252 .get_with_hash_without_recording(&*key, hash, ignore_if)
1253 };
1254 let insert = |v| self.insert_with_hash(key.clone(), hash, v);
1255
1256 let k = if need_key {
1257 Some(Arc::clone(&key))
1258 } else {
1259 None
1260 };
1261
1262 let type_id = ValueInitializer::<K, V, S>::type_id_for_optionally_get_with();
1263 let post_init = ValueInitializer::<K, V, S>::post_init_for_optionally_get_with;
1264
1265 match self
1266 .value_initializer
1267 .try_init_or_read(&key, type_id, get, init, insert, post_init)
1268 {
1269 InitResult::Initialized(v) => {
1270 crossbeam_epoch::pin().flush();
1271 Some(Entry::new(k, v, true, false))
1272 }
1273 InitResult::ReadExisting(v) => Some(Entry::new(k, v, false, false)),
1274 InitResult::InitErr(_) => {
1275 crossbeam_epoch::pin().flush();
1276 None
1277 }
1278 }
1279 }
1280
1281 /// Returns a _clone_ of the value corresponding to the key. If the value does
1282 /// not exist, evaluates the `init` closure, and inserts the value if `Ok(value)`
1283 /// was returned. If `Err(_)` was returned from the closure, this method does not
1284 /// insert a value and returns the `Err` wrapped by [`std::sync::Arc`][std-arc].
1285 ///
1286 /// [std-arc]: https://doc.rust-lang.org/stable/std/sync/struct.Arc.html
1287 ///
1288 /// # Concurrent calls on the same key
1289 ///
1290 /// This method guarantees that concurrent calls on the same not-existing key are
1291 /// coalesced into one evaluation of the `init` closure (as long as these
1292 /// closures return the same error type). Only one of the calls evaluates its
1293 /// closure, and other calls wait for that closure to complete.
1294 ///
1295 /// The following code snippet demonstrates this behavior:
1296 ///
1297 /// ```rust
1298 /// use moka::sync::Cache;
1299 /// use std::{path::Path, thread};
1300 ///
1301 /// /// This function tries to get the file size in bytes.
1302 /// fn get_file_size(thread_id: u8, path: impl AsRef<Path>) -> Result<u64, std::io::Error> {
1303 /// println!("get_file_size() called by thread {thread_id}.");
1304 /// Ok(std::fs::metadata(path)?.len())
1305 /// }
1306 ///
1307 /// let cache = Cache::new(100);
1308 ///
1309 /// // Spawn four threads.
1310 /// let threads: Vec<_> = (0..4_u8)
1311 /// .map(|thread_id| {
1312 /// let my_cache = cache.clone();
1313 /// thread::spawn(move || {
1314 /// println!("Thread {thread_id} started.");
1315 ///
1316 /// // Try to insert and get the value for key1. Although all four
1317 /// // threads will call `try_get_with` at the same time,
1318 /// // get_file_size() must be called only once.
1319 /// let value = my_cache.try_get_with(
1320 /// "key1",
1321 /// || get_file_size(thread_id, "./Cargo.toml"),
1322 /// );
1323 ///
1324 /// // Ensure the value exists now.
1325 /// assert!(value.is_ok());
1326 /// assert!(my_cache.get(&"key1").is_some());
1327 ///
1328 /// println!(
1329 /// "Thread {thread_id} got the value. (len: {})",
1330 /// value.unwrap()
1331 /// );
1332 /// })
1333 /// })
1334 /// .collect();
1335 ///
1336 /// // Wait all threads to complete.
1337 /// threads
1338 /// .into_iter()
1339 /// .for_each(|t| t.join().expect("Thread failed"));
1340 /// ```
1341 ///
1342 /// **Result**
1343 ///
1344 /// - `get_file_size()` was called exactly once by thread 1.
1345 /// - Other threads were blocked until thread 1 inserted the value.
1346 ///
1347 /// ```console
1348 /// Thread 1 started.
1349 /// Thread 2 started.
1350 /// get_file_size() called by thread 1.
1351 /// Thread 3 started.
1352 /// Thread 0 started.
1353 /// Thread 2 got the value. (len: 1466)
1354 /// Thread 0 got the value. (len: 1466)
1355 /// Thread 1 got the value. (len: 1466)
1356 /// Thread 3 got the value. (len: 1466)
1357 /// ```
1358 ///
1359 /// # Panics
1360 ///
1361 /// This method panics when the `init` closure has panicked. When it happens,
1362 /// only the caller whose `init` closure panicked will get the panic (e.g. only
1363 /// thread 1 in the above sample). If there are other calls in progress (e.g.
1364 /// thread 0, 2 and 3 above), this method will restart and resolve one of the
1365 /// remaining `init` closure.
1366 ///
1367 pub fn try_get_with<F, E>(&self, key: K, init: F) -> Result<V, Arc<E>>
1368 where
1369 F: FnOnce() -> Result<V, E>,
1370 E: Send + Sync + 'static,
1371 {
1372 let hash = self.base.hash(&key);
1373 let key = Arc::new(key);
1374 self.get_or_try_insert_with_hash_and_fun(key, hash, init, false)
1375 .map(Entry::into_value)
1376 }
1377
1378 /// Similar to [`try_get_with`](#method.try_get_with), but instead of passing an
1379 /// owned key, you can pass a reference to the key. If the key does not exist in
1380 /// the cache, the key will be cloned to create new entry in the cache.
1381 pub fn try_get_with_by_ref<F, E, Q>(&self, key: &Q, init: F) -> Result<V, Arc<E>>
1382 where
1383 F: FnOnce() -> Result<V, E>,
1384 E: Send + Sync + 'static,
1385 Q: Equivalent<K> + ToOwned<Owned = K> + Hash + ?Sized,
1386 {
1387 let hash = self.base.hash(key);
1388 self.get_or_try_insert_with_hash_by_ref_and_fun(key, hash, init, false)
1389 .map(Entry::into_value)
1390 }
1391
1392 pub(crate) fn get_or_try_insert_with_hash_and_fun<F, E>(
1393 &self,
1394 key: Arc<K>,
1395 hash: u64,
1396 init: F,
1397 need_key: bool,
1398 ) -> Result<Entry<K, V>, Arc<E>>
1399 where
1400 F: FnOnce() -> Result<V, E>,
1401 E: Send + Sync + 'static,
1402 {
1403 if let Some(entry) = self.get_with_hash(&*key, hash, need_key) {
1404 return Ok(entry);
1405 }
1406
1407 self.try_insert_with_hash_and_fun(key, hash, init, need_key)
1408 }
1409
1410 pub(crate) fn get_or_try_insert_with_hash_by_ref_and_fun<F, Q, E>(
1411 &self,
1412 key: &Q,
1413 hash: u64,
1414 init: F,
1415 need_key: bool,
1416 ) -> Result<Entry<K, V>, Arc<E>>
1417 where
1418 F: FnOnce() -> Result<V, E>,
1419 E: Send + Sync + 'static,
1420 Q: Equivalent<K> + ToOwned<Owned = K> + Hash + ?Sized,
1421 {
1422 if let Some(entry) = self.get_with_hash(key, hash, false) {
1423 return Ok(entry);
1424 }
1425
1426 let key = Arc::new(key.to_owned());
1427 self.try_insert_with_hash_and_fun(key, hash, init, need_key)
1428 }
1429
1430 pub(crate) fn try_insert_with_hash_and_fun<F, E>(
1431 &self,
1432 key: Arc<K>,
1433 hash: u64,
1434 init: F,
1435 need_key: bool,
1436 ) -> Result<Entry<K, V>, Arc<E>>
1437 where
1438 F: FnOnce() -> Result<V, E>,
1439 E: Send + Sync + 'static,
1440 {
1441 let get = || {
1442 let ignore_if = None as Option<&mut fn(&V) -> bool>;
1443 self.base
1444 .get_with_hash_without_recording(&*key, hash, ignore_if)
1445 };
1446 let insert = |v| self.insert_with_hash(key.clone(), hash, v);
1447
1448 let k = if need_key {
1449 Some(Arc::clone(&key))
1450 } else {
1451 None
1452 };
1453
1454 let type_id = ValueInitializer::<K, V, S>::type_id_for_try_get_with::<E>();
1455 let post_init = ValueInitializer::<K, V, S>::post_init_for_try_get_with;
1456
1457 match self
1458 .value_initializer
1459 .try_init_or_read(&key, type_id, get, init, insert, post_init)
1460 {
1461 InitResult::Initialized(v) => {
1462 crossbeam_epoch::pin().flush();
1463 Ok(Entry::new(k, v, true, false))
1464 }
1465 InitResult::ReadExisting(v) => Ok(Entry::new(k, v, false, false)),
1466 InitResult::InitErr(e) => {
1467 crossbeam_epoch::pin().flush();
1468 Err(e)
1469 }
1470 }
1471 }
1472
1473 /// Inserts a key-value pair into the cache.
1474 ///
1475 /// If the cache has this key present, the value is updated.
1476 pub fn insert(&self, key: K, value: V) {
1477 let hash = self.base.hash(&key);
1478 let key = Arc::new(key);
1479 self.insert_with_hash(key, hash, value);
1480 }
1481
1482 pub(crate) fn insert_with_hash(&self, key: Arc<K>, hash: u64, value: V) {
1483 if self.base.is_map_disabled() {
1484 return;
1485 }
1486
1487 let (op, now) = self.base.do_insert_with_hash(key, hash, value);
1488 let hk = self.base.housekeeper.as_ref();
1489 Self::schedule_write_op(
1490 self.base.inner.as_ref(),
1491 &self.base.write_op_ch,
1492 op,
1493 now,
1494 hk,
1495 )
1496 .expect("Failed to insert");
1497 }
1498
1499 pub(crate) fn compute_with_hash_and_fun<F>(
1500 &self,
1501 key: Arc<K>,
1502 hash: u64,
1503 f: F,
1504 ) -> compute::CompResult<K, V>
1505 where
1506 F: FnOnce(Option<Entry<K, V>>) -> compute::Op<V>,
1507 {
1508 let post_init = ValueInitializer::<K, V, S>::post_init_for_compute_with;
1509 match self
1510 .value_initializer
1511 .try_compute(key, hash, self, f, post_init, true)
1512 {
1513 Ok(result) => result,
1514 Err(_) => unreachable!(),
1515 }
1516 }
1517
1518 pub(crate) fn try_compute_with_hash_and_fun<F, E>(
1519 &self,
1520 key: Arc<K>,
1521 hash: u64,
1522 f: F,
1523 ) -> Result<compute::CompResult<K, V>, E>
1524 where
1525 F: FnOnce(Option<Entry<K, V>>) -> Result<compute::Op<V>, E>,
1526 E: Send + Sync + 'static,
1527 {
1528 let post_init = ValueInitializer::<K, V, S>::post_init_for_try_compute_with;
1529 self.value_initializer
1530 .try_compute(key, hash, self, f, post_init, true)
1531 }
1532
1533 pub(crate) fn upsert_with_hash_and_fun<F>(&self, key: Arc<K>, hash: u64, f: F) -> Entry<K, V>
1534 where
1535 F: FnOnce(Option<Entry<K, V>>) -> V,
1536 {
1537 let post_init = ValueInitializer::<K, V, S>::post_init_for_upsert_with;
1538 match self
1539 .value_initializer
1540 .try_compute(key, hash, self, f, post_init, false)
1541 {
1542 Ok(CompResult::Inserted(entry) | CompResult::ReplacedWith(entry)) => entry,
1543 _ => unreachable!(),
1544 }
1545 }
1546
1547 /// Discards any cached value for the key.
1548 ///
1549 /// If you need to get a the value that has been discarded, use the
1550 /// [`remove`](#method.remove) method instead.
1551 ///
1552 /// The key may be any borrowed form of the cache's key type, but `Hash` and `Eq`
1553 /// on the borrowed form _must_ match those for the key type.
1554 pub fn invalidate<Q>(&self, key: &Q)
1555 where
1556 Q: Equivalent<K> + Hash + ?Sized,
1557 {
1558 let hash = self.base.hash(key);
1559 self.invalidate_with_hash(key, hash, false);
1560 }
1561
1562 /// Discards any cached value for the key and returns a _clone_ of the value.
1563 ///
1564 /// If you do not need to get the value that has been discarded, use the
1565 /// [`invalidate`](#method.invalidate) method instead.
1566 ///
1567 /// The key may be any borrowed form of the cache's key type, but `Hash` and `Eq`
1568 /// on the borrowed form _must_ match those for the key type.
1569 pub fn remove<Q>(&self, key: &Q) -> Option<V>
1570 where
1571 Q: Equivalent<K> + Hash + ?Sized,
1572 {
1573 let hash = self.base.hash(key);
1574 self.invalidate_with_hash(key, hash, true)
1575 }
1576
1577 pub(crate) fn invalidate_with_hash<Q>(&self, key: &Q, hash: u64, need_value: bool) -> Option<V>
1578 where
1579 Q: Equivalent<K> + Hash + ?Sized,
1580 {
1581 // Lock the key for removal if blocking removal notification is enabled.
1582 let mut kl = None;
1583 let mut klg = None;
1584 if self.base.is_removal_notifier_enabled() {
1585 // To lock the key, we have to get Arc<K> for key (&Q).
1586 //
1587 // TODO: Enhance this if possible. This is rather hack now because
1588 // it cannot prevent race conditions like this:
1589 //
1590 // 1. We miss the key because it does not exist. So we do not lock
1591 // the key.
1592 // 2. Somebody else (other thread) inserts the key.
1593 // 3. We remove the entry for the key, but without the key lock!
1594 //
1595 if let Some(arc_key) = self.base.get_key_with_hash(key, hash) {
1596 kl = self.base.maybe_key_lock(&arc_key);
1597 klg = kl.as_ref().map(|kl| kl.lock());
1598 }
1599 }
1600
1601 match self.base.remove_entry(key, hash) {
1602 None => None,
1603 Some(kv) => {
1604 let now = self.base.current_time();
1605
1606 let info = kv.entry.entry_info();
1607 let entry_gen = info.incr_entry_gen();
1608
1609 if self.base.is_removal_notifier_enabled() {
1610 self.base.notify_invalidate(&kv.key, &kv.entry);
1611 }
1612 // Drop the locks before scheduling write op to avoid a potential
1613 // dead lock. (Scheduling write can do spin lock when the queue is
1614 // full, and queue will be drained by the housekeeping thread that
1615 // can lock the same key)
1616 std::mem::drop(klg);
1617 std::mem::drop(kl);
1618
1619 let maybe_v = if need_value {
1620 Some(kv.entry.value.clone())
1621 } else {
1622 None
1623 };
1624
1625 let op = WriteOp::Remove {
1626 kv_entry: kv,
1627 entry_gen,
1628 };
1629 let hk = self.base.housekeeper.as_ref();
1630 Self::schedule_write_op(
1631 self.base.inner.as_ref(),
1632 &self.base.write_op_ch,
1633 op,
1634 now,
1635 hk,
1636 )
1637 .expect("Failed to remove");
1638 crossbeam_epoch::pin().flush();
1639 maybe_v
1640 }
1641 }
1642 }
1643
1644 /// Discards all cached values.
1645 ///
1646 /// This method returns immediately by just setting the current time as the
1647 /// invalidation time. `get` and other retrieval methods are guaranteed not to
1648 /// return the entries inserted before or at the invalidation time.
1649 ///
1650 /// The actual removal of the invalidated entries is done as a maintenance task
1651 /// driven by a user thread. For more details, see
1652 /// [the Maintenance Tasks section](../index.html#maintenance-tasks) in the crate
1653 /// level documentation.
1654 ///
1655 /// Like the `invalidate` method, this method does not clear the historic
1656 /// popularity estimator of keys so that it retains the client activities of
1657 /// trying to retrieve an item.
1658 pub fn invalidate_all(&self) {
1659 self.base.invalidate_all();
1660 }
1661
1662 /// Discards cached values that satisfy a predicate.
1663 ///
1664 /// `invalidate_entries_if` takes a closure that returns `true` or `false`. The
1665 /// closure is called against each cached entry inserted before or at the time
1666 /// when this method was called. If the closure returns `true` that entry will be
1667 /// evicted from the cache.
1668 ///
1669 /// This method returns immediately by not actually removing the invalidated
1670 /// entries. Instead, it just sets the predicate to the cache with the time when
1671 /// this method was called. The actual removal of the invalidated entries is done
1672 /// as a maintenance task driven by a user thread. For more details, see
1673 /// [the Maintenance Tasks section](../index.html#maintenance-tasks) in the crate
1674 /// level documentation.
1675 ///
1676 /// Also the `get` and other retrieval methods will apply the closure to a cached
1677 /// entry to determine if it should have been invalidated. Therefore, it is
1678 /// guaranteed that these methods must not return invalidated values.
1679 ///
1680 /// Note that you must call
1681 /// [`CacheBuilder::support_invalidation_closures`][support-invalidation-closures]
1682 /// at the cache creation time as the cache needs to maintain additional internal
1683 /// data structures to support this method. Otherwise, calling this method will
1684 /// fail with a
1685 /// [`PredicateError::InvalidationClosuresDisabled`][invalidation-disabled-error].
1686 ///
1687 /// Like the `invalidate` method, this method does not clear the historic
1688 /// popularity estimator of keys so that it retains the client activities of
1689 /// trying to retrieve an item.
1690 ///
1691 /// [support-invalidation-closures]:
1692 /// ./struct.CacheBuilder.html#method.support_invalidation_closures
1693 /// [invalidation-disabled-error]:
1694 /// ../enum.PredicateError.html#variant.InvalidationClosuresDisabled
1695 pub fn invalidate_entries_if<F>(&self, predicate: F) -> Result<PredicateId, PredicateError>
1696 where
1697 F: Fn(&K, &V) -> bool + Send + Sync + 'static,
1698 {
1699 self.base.invalidate_entries_if(Arc::new(predicate))
1700 }
1701
1702 pub(crate) fn invalidate_entries_with_arc_fun<F>(
1703 &self,
1704 predicate: Arc<F>,
1705 ) -> Result<PredicateId, PredicateError>
1706 where
1707 F: Fn(&K, &V) -> bool + Send + Sync + 'static,
1708 {
1709 self.base.invalidate_entries_if(predicate)
1710 }
1711
1712 /// Creates an iterator visiting all key-value pairs in arbitrary order. The
1713 /// iterator element type is `(Arc<K>, V)`, where `V` is a clone of a stored
1714 /// value.
1715 ///
1716 /// Iterators do not block concurrent reads and writes on the cache. An entry can
1717 /// be inserted to, invalidated or evicted from a cache while iterators are alive
1718 /// on the same cache.
1719 ///
1720 /// Unlike the `get` method, visiting entries via an iterator do not update the
1721 /// historic popularity estimator or reset idle timers for keys.
1722 ///
1723 /// # Guarantees
1724 ///
1725 /// In order to allow concurrent access to the cache, iterator's `next` method
1726 /// does _not_ guarantee the following:
1727 ///
1728 /// - It does not guarantee to return a key-value pair (an entry) if its key has
1729 /// been inserted to the cache _after_ the iterator was created.
1730 /// - Such an entry may or may not be returned depending on key's hash and
1731 /// timing.
1732 ///
1733 /// and the `next` method guarantees the followings:
1734 ///
1735 /// - It guarantees not to return the same entry more than once.
1736 /// - It guarantees not to return an entry if it has been removed from the cache
1737 /// after the iterator was created.
1738 /// - Note: An entry can be removed by following reasons:
1739 /// - Manually invalidated.
1740 /// - Expired (e.g. time-to-live).
1741 /// - Evicted as the cache capacity exceeded.
1742 ///
1743 /// # Examples
1744 ///
1745 /// ```rust
1746 /// use moka::sync::Cache;
1747 ///
1748 /// let cache = Cache::new(100);
1749 /// cache.insert("Julia", 14);
1750 ///
1751 /// let mut iter = cache.iter();
1752 /// let (k, v) = iter.next().unwrap(); // (Arc<K>, V)
1753 /// assert_eq!(*k, "Julia");
1754 /// assert_eq!(v, 14);
1755 ///
1756 /// assert!(iter.next().is_none());
1757 /// ```
1758 ///
1759 pub fn iter(&self) -> Iter<'_, K, V> {
1760 Iter::with_single_cache_segment(&self.base, self.num_cht_segments())
1761 }
1762
1763 /// Performs any pending maintenance operations needed by the cache.
1764 pub fn run_pending_tasks(&self) {
1765 if let Some(hk) = &self.base.housekeeper {
1766 hk.run_pending_tasks(&*self.base.inner);
1767 }
1768 }
1769}
1770
1771impl<'a, K, V, S> IntoIterator for &'a Cache<K, V, S>
1772where
1773 K: Hash + Eq + Send + Sync + 'static,
1774 V: Clone + Send + Sync + 'static,
1775 S: BuildHasher + Clone + Send + Sync + 'static,
1776{
1777 type Item = (Arc<K>, V);
1778
1779 type IntoIter = Iter<'a, K, V>;
1780
1781 fn into_iter(self) -> Self::IntoIter {
1782 self.iter()
1783 }
1784}
1785
1786//
1787// Iterator support
1788//
1789impl<K, V, S> ScanningGet<K, V> for Cache<K, V, S>
1790where
1791 K: Hash + Eq + Send + Sync + 'static,
1792 V: Clone + Send + Sync + 'static,
1793 S: BuildHasher + Clone + Send + Sync + 'static,
1794{
1795 fn num_cht_segments(&self) -> usize {
1796 self.base.num_cht_segments()
1797 }
1798
1799 fn scanning_get(&self, key: &Arc<K>) -> Option<V> {
1800 self.base.scanning_get(key)
1801 }
1802
1803 fn keys(&self, cht_segment: usize) -> Option<Vec<Arc<K>>> {
1804 self.base.keys(cht_segment)
1805 }
1806}
1807
1808//
1809// private methods
1810//
1811impl<K, V, S> Cache<K, V, S>
1812where
1813 K: Hash + Eq + Send + Sync + 'static,
1814 V: Clone + Send + Sync + 'static,
1815 S: BuildHasher + Clone + Send + Sync + 'static,
1816{
1817 // TODO: Like future::Cache, move this method to BaseCache.
1818 #[inline]
1819 fn schedule_write_op(
1820 inner: &impl InnerSync,
1821 ch: &Sender<WriteOp<K, V>>,
1822 op: WriteOp<K, V>,
1823 now: Instant,
1824 housekeeper: Option<&HouseKeeperArc>,
1825 ) -> Result<(), TrySendError<WriteOp<K, V>>> {
1826 let mut op = op;
1827
1828 // NOTES:
1829 // - This will block when the channel is full.
1830 // - We are doing a busy-loop here. We were originally calling `ch.send(op)?`,
1831 // but we got a notable performance degradation.
1832 loop {
1833 BaseCache::<K, V, S>::apply_reads_writes_if_needed(inner, ch, now, housekeeper);
1834 match ch.try_send(op) {
1835 Ok(()) => break,
1836 Err(TrySendError::Full(op1)) => {
1837 op = op1;
1838 std::thread::sleep(Duration::from_micros(WRITE_RETRY_INTERVAL_MICROS));
1839 }
1840 Err(e @ TrySendError::Disconnected(_)) => return Err(e),
1841 }
1842 }
1843 Ok(())
1844 }
1845}
1846
1847// For unit tests.
1848#[cfg(test)]
1849impl<K, V, S> Cache<K, V, S> {
1850 pub(crate) fn is_table_empty(&self) -> bool {
1851 self.entry_count() == 0
1852 }
1853
1854 pub(crate) fn is_waiter_map_empty(&self) -> bool {
1855 self.value_initializer.waiter_count() == 0
1856 }
1857}
1858
1859#[cfg(test)]
1860impl<K, V, S> Cache<K, V, S>
1861where
1862 K: Hash + Eq + Send + Sync + 'static,
1863 V: Clone + Send + Sync + 'static,
1864 S: BuildHasher + Clone + Send + Sync + 'static,
1865{
1866 pub(crate) fn invalidation_predicate_count(&self) -> usize {
1867 self.base.invalidation_predicate_count()
1868 }
1869
1870 pub(crate) fn reconfigure_for_testing(&mut self) {
1871 self.base.reconfigure_for_testing();
1872 }
1873
1874 pub(crate) fn key_locks_map_is_empty(&self) -> bool {
1875 self.base.key_locks_map_is_empty()
1876 }
1877}
1878
1879// To see the debug prints, run test as `cargo test -- --nocapture`
1880#[cfg(test)]
1881mod tests {
1882 use super::Cache;
1883 use crate::{
1884 common::{time::Clock, HousekeeperConfig},
1885 notification::RemovalCause,
1886 policy::{test_utils::ExpiryCallCounters, EvictionPolicy},
1887 Expiry,
1888 };
1889
1890 use parking_lot::Mutex;
1891 use std::{
1892 convert::Infallible,
1893 sync::{
1894 atomic::{AtomicU8, Ordering},
1895 Arc,
1896 },
1897 time::{Duration, Instant as StdInstant},
1898 };
1899
1900 #[test]
1901 fn max_capacity_zero() {
1902 let mut cache = Cache::new(0);
1903 cache.reconfigure_for_testing();
1904
1905 // Make the cache exterior immutable.
1906 let cache = cache;
1907
1908 cache.insert(0, ());
1909
1910 assert!(!cache.contains_key(&0));
1911 assert!(cache.get(&0).is_none());
1912 cache.run_pending_tasks();
1913 assert!(!cache.contains_key(&0));
1914 assert!(cache.get(&0).is_none());
1915 assert_eq!(cache.entry_count(), 0)
1916 }
1917
1918 #[test]
1919 fn basic_single_thread() {
1920 // The following `Vec`s will hold actual and expected notifications.
1921 let actual = Arc::new(Mutex::new(Vec::new()));
1922 let mut expected = Vec::new();
1923
1924 // Create an eviction listener.
1925 let a1 = Arc::clone(&actual);
1926 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
1927
1928 // Create a cache with the eviction listener.
1929 let mut cache = Cache::builder()
1930 .max_capacity(3)
1931 .eviction_listener(listener)
1932 .build();
1933 cache.reconfigure_for_testing();
1934
1935 // Make the cache exterior immutable.
1936 let cache = cache;
1937
1938 cache.insert("a", "alice");
1939 cache.insert("b", "bob");
1940 assert_eq!(cache.get(&"a"), Some("alice"));
1941 assert!(cache.contains_key(&"a"));
1942 assert!(cache.contains_key(&"b"));
1943 assert_eq!(cache.get(&"b"), Some("bob"));
1944 cache.run_pending_tasks();
1945 // counts: a -> 1, b -> 1
1946
1947 cache.insert("c", "cindy");
1948 assert_eq!(cache.get(&"c"), Some("cindy"));
1949 assert!(cache.contains_key(&"c"));
1950 // counts: a -> 1, b -> 1, c -> 1
1951 cache.run_pending_tasks();
1952
1953 assert!(cache.contains_key(&"a"));
1954 assert_eq!(cache.get(&"a"), Some("alice"));
1955 assert_eq!(cache.get(&"b"), Some("bob"));
1956 assert!(cache.contains_key(&"b"));
1957 cache.run_pending_tasks();
1958 // counts: a -> 2, b -> 2, c -> 1
1959
1960 // "d" should not be admitted because its frequency is too low.
1961 cache.insert("d", "david"); // count: d -> 0
1962 expected.push((Arc::new("d"), "david", RemovalCause::Size));
1963 cache.run_pending_tasks();
1964 assert_eq!(cache.get(&"d"), None); // d -> 1
1965 assert!(!cache.contains_key(&"d"));
1966
1967 cache.insert("d", "david");
1968 expected.push((Arc::new("d"), "david", RemovalCause::Size));
1969 cache.run_pending_tasks();
1970 assert!(!cache.contains_key(&"d"));
1971 assert_eq!(cache.get(&"d"), None); // d -> 2
1972
1973 // "d" should be admitted and "c" should be evicted
1974 // because d's frequency is higher than c's.
1975 cache.insert("d", "dennis");
1976 expected.push((Arc::new("c"), "cindy", RemovalCause::Size));
1977 cache.run_pending_tasks();
1978 assert_eq!(cache.get(&"a"), Some("alice"));
1979 assert_eq!(cache.get(&"b"), Some("bob"));
1980 assert_eq!(cache.get(&"c"), None);
1981 assert_eq!(cache.get(&"d"), Some("dennis"));
1982 assert!(cache.contains_key(&"a"));
1983 assert!(cache.contains_key(&"b"));
1984 assert!(!cache.contains_key(&"c"));
1985 assert!(cache.contains_key(&"d"));
1986
1987 cache.invalidate(&"b");
1988 expected.push((Arc::new("b"), "bob", RemovalCause::Explicit));
1989 cache.run_pending_tasks();
1990 assert_eq!(cache.get(&"b"), None);
1991 assert!(!cache.contains_key(&"b"));
1992
1993 assert!(cache.remove(&"b").is_none());
1994 assert_eq!(cache.remove(&"d"), Some("dennis"));
1995 expected.push((Arc::new("d"), "dennis", RemovalCause::Explicit));
1996 cache.run_pending_tasks();
1997 assert_eq!(cache.get(&"d"), None);
1998 assert!(!cache.contains_key(&"d"));
1999
2000 verify_notification_vec(&cache, actual, &expected);
2001 assert!(cache.key_locks_map_is_empty());
2002 }
2003
2004 #[test]
2005 fn basic_lru_single_thread() {
2006 // The following `Vec`s will hold actual and expected notifications.
2007 let actual = Arc::new(Mutex::new(Vec::new()));
2008 let mut expected = Vec::new();
2009
2010 // Create an eviction listener.
2011 let a1 = Arc::clone(&actual);
2012 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
2013
2014 // Create a cache with the eviction listener.
2015 let mut cache = Cache::builder()
2016 .max_capacity(3)
2017 .eviction_policy(EvictionPolicy::lru())
2018 .eviction_listener(listener)
2019 .build();
2020 cache.reconfigure_for_testing();
2021
2022 // Make the cache exterior immutable.
2023 let cache = cache;
2024
2025 cache.insert("a", "alice");
2026 cache.insert("b", "bob");
2027 assert_eq!(cache.get(&"a"), Some("alice"));
2028 assert!(cache.contains_key(&"a"));
2029 assert!(cache.contains_key(&"b"));
2030 assert_eq!(cache.get(&"b"), Some("bob"));
2031 cache.run_pending_tasks();
2032 // a -> b
2033
2034 cache.insert("c", "cindy");
2035 assert_eq!(cache.get(&"c"), Some("cindy"));
2036 assert!(cache.contains_key(&"c"));
2037 cache.run_pending_tasks();
2038 // a -> b -> c
2039
2040 assert!(cache.contains_key(&"a"));
2041 assert_eq!(cache.get(&"a"), Some("alice"));
2042 assert_eq!(cache.get(&"b"), Some("bob"));
2043 assert!(cache.contains_key(&"b"));
2044 cache.run_pending_tasks();
2045 // c -> a -> b
2046
2047 // "d" should be admitted because the cache uses the LRU strategy.
2048 cache.insert("d", "david");
2049 // "c" is the LRU and should have be evicted.
2050 expected.push((Arc::new("c"), "cindy", RemovalCause::Size));
2051 cache.run_pending_tasks();
2052
2053 assert_eq!(cache.get(&"a"), Some("alice"));
2054 assert_eq!(cache.get(&"b"), Some("bob"));
2055 assert_eq!(cache.get(&"c"), None);
2056 assert_eq!(cache.get(&"d"), Some("david"));
2057 assert!(cache.contains_key(&"a"));
2058 assert!(cache.contains_key(&"b"));
2059 assert!(!cache.contains_key(&"c"));
2060 assert!(cache.contains_key(&"d"));
2061 cache.run_pending_tasks();
2062 // a -> b -> d
2063
2064 cache.invalidate(&"b");
2065 expected.push((Arc::new("b"), "bob", RemovalCause::Explicit));
2066 cache.run_pending_tasks();
2067 // a -> d
2068 assert_eq!(cache.get(&"b"), None);
2069 assert!(!cache.contains_key(&"b"));
2070
2071 assert!(cache.remove(&"b").is_none());
2072 assert_eq!(cache.remove(&"d"), Some("david"));
2073 expected.push((Arc::new("d"), "david", RemovalCause::Explicit));
2074 cache.run_pending_tasks();
2075 // a
2076 assert_eq!(cache.get(&"d"), None);
2077 assert!(!cache.contains_key(&"d"));
2078
2079 cache.insert("e", "emily");
2080 cache.insert("f", "frank");
2081 // "a" should be evicted because it is the LRU.
2082 cache.insert("g", "gina");
2083 expected.push((Arc::new("a"), "alice", RemovalCause::Size));
2084 cache.run_pending_tasks();
2085 // e -> f -> g
2086 assert_eq!(cache.get(&"a"), None);
2087 assert_eq!(cache.get(&"e"), Some("emily"));
2088 assert_eq!(cache.get(&"f"), Some("frank"));
2089 assert_eq!(cache.get(&"g"), Some("gina"));
2090 assert!(!cache.contains_key(&"a"));
2091 assert!(cache.contains_key(&"e"));
2092 assert!(cache.contains_key(&"f"));
2093 assert!(cache.contains_key(&"g"));
2094
2095 verify_notification_vec(&cache, actual, &expected);
2096 assert!(cache.key_locks_map_is_empty());
2097 }
2098
2099 #[test]
2100 fn size_aware_eviction() {
2101 let weigher = |_k: &&str, v: &(&str, u32)| v.1;
2102
2103 let alice = ("alice", 10);
2104 let bob = ("bob", 15);
2105 let bill = ("bill", 20);
2106 let cindy = ("cindy", 5);
2107 let david = ("david", 15);
2108 let dennis = ("dennis", 15);
2109
2110 // The following `Vec`s will hold actual and expected notifications.
2111 let actual = Arc::new(Mutex::new(Vec::new()));
2112 let mut expected = Vec::new();
2113
2114 // Create an eviction listener.
2115 let a1 = Arc::clone(&actual);
2116 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
2117
2118 // Create a cache with the eviction listener.
2119 let mut cache = Cache::builder()
2120 .max_capacity(31)
2121 .weigher(weigher)
2122 .eviction_listener(listener)
2123 .build();
2124 cache.reconfigure_for_testing();
2125
2126 // Make the cache exterior immutable.
2127 let cache = cache;
2128
2129 cache.insert("a", alice);
2130 cache.insert("b", bob);
2131 assert_eq!(cache.get(&"a"), Some(alice));
2132 assert!(cache.contains_key(&"a"));
2133 assert!(cache.contains_key(&"b"));
2134 assert_eq!(cache.get(&"b"), Some(bob));
2135 cache.run_pending_tasks();
2136 // order (LRU -> MRU) and counts: a -> 1, b -> 1
2137
2138 cache.insert("c", cindy);
2139 assert_eq!(cache.get(&"c"), Some(cindy));
2140 assert!(cache.contains_key(&"c"));
2141 // order and counts: a -> 1, b -> 1, c -> 1
2142 cache.run_pending_tasks();
2143
2144 assert!(cache.contains_key(&"a"));
2145 assert_eq!(cache.get(&"a"), Some(alice));
2146 assert_eq!(cache.get(&"b"), Some(bob));
2147 assert!(cache.contains_key(&"b"));
2148 cache.run_pending_tasks();
2149 // order and counts: c -> 1, a -> 2, b -> 2
2150
2151 // To enter "d" (weight: 15), it needs to evict "c" (w: 5) and "a" (w: 10).
2152 // "d" must have higher count than 3, which is the aggregated count
2153 // of "a" and "c".
2154 cache.insert("d", david); // count: d -> 0
2155 expected.push((Arc::new("d"), david, RemovalCause::Size));
2156 cache.run_pending_tasks();
2157 assert_eq!(cache.get(&"d"), None); // d -> 1
2158 assert!(!cache.contains_key(&"d"));
2159
2160 cache.insert("d", david);
2161 expected.push((Arc::new("d"), david, RemovalCause::Size));
2162 cache.run_pending_tasks();
2163 assert!(!cache.contains_key(&"d"));
2164 assert_eq!(cache.get(&"d"), None); // d -> 2
2165
2166 cache.insert("d", david);
2167 expected.push((Arc::new("d"), david, RemovalCause::Size));
2168 cache.run_pending_tasks();
2169 assert_eq!(cache.get(&"d"), None); // d -> 3
2170 assert!(!cache.contains_key(&"d"));
2171
2172 cache.insert("d", david);
2173 expected.push((Arc::new("d"), david, RemovalCause::Size));
2174 cache.run_pending_tasks();
2175 assert!(!cache.contains_key(&"d"));
2176 assert_eq!(cache.get(&"d"), None); // d -> 4
2177
2178 // Finally "d" should be admitted by evicting "c" and "a".
2179 cache.insert("d", dennis);
2180 expected.push((Arc::new("c"), cindy, RemovalCause::Size));
2181 expected.push((Arc::new("a"), alice, RemovalCause::Size));
2182 cache.run_pending_tasks();
2183 assert_eq!(cache.get(&"a"), None);
2184 assert_eq!(cache.get(&"b"), Some(bob));
2185 assert_eq!(cache.get(&"c"), None);
2186 assert_eq!(cache.get(&"d"), Some(dennis));
2187 assert!(!cache.contains_key(&"a"));
2188 assert!(cache.contains_key(&"b"));
2189 assert!(!cache.contains_key(&"c"));
2190 assert!(cache.contains_key(&"d"));
2191
2192 // Update "b" with "bill" (w: 15 -> 20). This should evict "d" (w: 15).
2193 cache.insert("b", bill);
2194 expected.push((Arc::new("b"), bob, RemovalCause::Replaced));
2195 expected.push((Arc::new("d"), dennis, RemovalCause::Size));
2196 cache.run_pending_tasks();
2197 assert_eq!(cache.get(&"b"), Some(bill));
2198 assert_eq!(cache.get(&"d"), None);
2199 assert!(cache.contains_key(&"b"));
2200 assert!(!cache.contains_key(&"d"));
2201
2202 // Re-add "a" (w: 10) and update "b" with "bob" (w: 20 -> 15).
2203 cache.insert("a", alice);
2204 cache.insert("b", bob);
2205 expected.push((Arc::new("b"), bill, RemovalCause::Replaced));
2206 cache.run_pending_tasks();
2207 assert_eq!(cache.get(&"a"), Some(alice));
2208 assert_eq!(cache.get(&"b"), Some(bob));
2209 assert_eq!(cache.get(&"d"), None);
2210 assert!(cache.contains_key(&"a"));
2211 assert!(cache.contains_key(&"b"));
2212 assert!(!cache.contains_key(&"d"));
2213
2214 // Verify the sizes.
2215 assert_eq!(cache.entry_count(), 2);
2216 assert_eq!(cache.weighted_size(), 25);
2217
2218 verify_notification_vec(&cache, actual, &expected);
2219 assert!(cache.key_locks_map_is_empty());
2220 }
2221
2222 #[test]
2223 fn basic_multi_threads() {
2224 let num_threads = 4;
2225 let cache = Cache::new(100);
2226
2227 // https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
2228 #[allow(clippy::needless_collect)]
2229 let handles = (0..num_threads)
2230 .map(|id| {
2231 let cache = cache.clone();
2232 std::thread::spawn(move || {
2233 cache.insert(10, format!("{id}-100"));
2234 cache.get(&10);
2235 cache.insert(20, format!("{id}-200"));
2236 cache.invalidate(&10);
2237 })
2238 })
2239 .collect::<Vec<_>>();
2240
2241 handles.into_iter().for_each(|h| h.join().expect("Failed"));
2242
2243 assert!(cache.get(&10).is_none());
2244 assert!(cache.get(&20).is_some());
2245 assert!(!cache.contains_key(&10));
2246 assert!(cache.contains_key(&20));
2247 }
2248
2249 #[test]
2250 fn invalidate_all() {
2251 // The following `Vec`s will hold actual and expected notifications.
2252 let actual = Arc::new(Mutex::new(Vec::new()));
2253 let mut expected = Vec::new();
2254
2255 // Create an eviction listener.
2256 let a1 = Arc::clone(&actual);
2257 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
2258
2259 // Create a cache with the eviction listener.
2260 let mut cache = Cache::builder()
2261 .max_capacity(100)
2262 .eviction_listener(listener)
2263 .build();
2264 cache.reconfigure_for_testing();
2265
2266 // Make the cache exterior immutable.
2267 let cache = cache;
2268
2269 cache.insert("a", "alice");
2270 cache.insert("b", "bob");
2271 cache.insert("c", "cindy");
2272 assert_eq!(cache.get(&"a"), Some("alice"));
2273 assert_eq!(cache.get(&"b"), Some("bob"));
2274 assert_eq!(cache.get(&"c"), Some("cindy"));
2275 assert!(cache.contains_key(&"a"));
2276 assert!(cache.contains_key(&"b"));
2277 assert!(cache.contains_key(&"c"));
2278
2279 // `cache.run_pending_tasks()` is no longer needed here before invalidating. The last
2280 // modified timestamp of the entries were updated when they were inserted.
2281 // https://github.com/moka-rs/moka/issues/155
2282
2283 cache.invalidate_all();
2284 expected.push((Arc::new("a"), "alice", RemovalCause::Explicit));
2285 expected.push((Arc::new("b"), "bob", RemovalCause::Explicit));
2286 expected.push((Arc::new("c"), "cindy", RemovalCause::Explicit));
2287 cache.run_pending_tasks();
2288
2289 cache.insert("d", "david");
2290 cache.run_pending_tasks();
2291
2292 assert!(cache.get(&"a").is_none());
2293 assert!(cache.get(&"b").is_none());
2294 assert!(cache.get(&"c").is_none());
2295 assert_eq!(cache.get(&"d"), Some("david"));
2296 assert!(!cache.contains_key(&"a"));
2297 assert!(!cache.contains_key(&"b"));
2298 assert!(!cache.contains_key(&"c"));
2299 assert!(cache.contains_key(&"d"));
2300
2301 verify_notification_vec(&cache, actual, &expected);
2302 }
2303
2304 #[test]
2305 fn invalidate_entries_if() -> Result<(), Box<dyn std::error::Error>> {
2306 use std::collections::HashSet;
2307
2308 // The following `Vec`s will hold actual and expected notifications.
2309 let actual = Arc::new(Mutex::new(Vec::new()));
2310 let mut expected = Vec::new();
2311
2312 // Create an eviction listener.
2313 let a1 = Arc::clone(&actual);
2314 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
2315
2316 let (clock, mock) = Clock::mock();
2317
2318 // Create a cache with the eviction listener.
2319 let mut cache = Cache::builder()
2320 .max_capacity(100)
2321 .support_invalidation_closures()
2322 .eviction_listener(listener)
2323 .clock(clock)
2324 .build();
2325 cache.reconfigure_for_testing();
2326
2327 // Make the cache exterior immutable.
2328 let cache = cache;
2329
2330 cache.insert(0, "alice");
2331 cache.insert(1, "bob");
2332 cache.insert(2, "alex");
2333 cache.run_pending_tasks();
2334
2335 mock.increment(Duration::from_secs(5)); // 5 secs from the start.
2336 cache.run_pending_tasks();
2337
2338 assert_eq!(cache.get(&0), Some("alice"));
2339 assert_eq!(cache.get(&1), Some("bob"));
2340 assert_eq!(cache.get(&2), Some("alex"));
2341 assert!(cache.contains_key(&0));
2342 assert!(cache.contains_key(&1));
2343 assert!(cache.contains_key(&2));
2344
2345 let names = ["alice", "alex"].iter().cloned().collect::<HashSet<_>>();
2346 cache.invalidate_entries_if(move |_k, &v| names.contains(v))?;
2347 assert_eq!(cache.base.invalidation_predicate_count(), 1);
2348 expected.push((Arc::new(0), "alice", RemovalCause::Explicit));
2349 expected.push((Arc::new(2), "alex", RemovalCause::Explicit));
2350
2351 mock.increment(Duration::from_secs(5)); // 10 secs from the start.
2352
2353 cache.insert(3, "alice");
2354
2355 // Run the invalidation task and wait for it to finish. (TODO: Need a better way than sleeping)
2356 cache.run_pending_tasks(); // To submit the invalidation task.
2357 std::thread::sleep(Duration::from_millis(200));
2358 cache.run_pending_tasks(); // To process the task result.
2359 std::thread::sleep(Duration::from_millis(200));
2360
2361 assert!(cache.get(&0).is_none());
2362 assert!(cache.get(&2).is_none());
2363 assert_eq!(cache.get(&1), Some("bob"));
2364 // This should survive as it was inserted after calling invalidate_entries_if.
2365 assert_eq!(cache.get(&3), Some("alice"));
2366
2367 assert!(!cache.contains_key(&0));
2368 assert!(cache.contains_key(&1));
2369 assert!(!cache.contains_key(&2));
2370 assert!(cache.contains_key(&3));
2371
2372 assert_eq!(cache.entry_count(), 2);
2373 assert_eq!(cache.invalidation_predicate_count(), 0);
2374
2375 mock.increment(Duration::from_secs(5)); // 15 secs from the start.
2376
2377 cache.invalidate_entries_if(|_k, &v| v == "alice")?;
2378 cache.invalidate_entries_if(|_k, &v| v == "bob")?;
2379 assert_eq!(cache.invalidation_predicate_count(), 2);
2380 // key 1 was inserted before key 3.
2381 expected.push((Arc::new(1), "bob", RemovalCause::Explicit));
2382 expected.push((Arc::new(3), "alice", RemovalCause::Explicit));
2383
2384 // Run the invalidation task and wait for it to finish. (TODO: Need a better way than sleeping)
2385 cache.run_pending_tasks(); // To submit the invalidation task.
2386 std::thread::sleep(Duration::from_millis(200));
2387 cache.run_pending_tasks(); // To process the task result.
2388 std::thread::sleep(Duration::from_millis(200));
2389
2390 assert!(cache.get(&1).is_none());
2391 assert!(cache.get(&3).is_none());
2392
2393 assert!(!cache.contains_key(&1));
2394 assert!(!cache.contains_key(&3));
2395
2396 assert_eq!(cache.entry_count(), 0);
2397 assert_eq!(cache.invalidation_predicate_count(), 0);
2398
2399 verify_notification_vec(&cache, actual, &expected);
2400
2401 Ok(())
2402 }
2403
2404 #[test]
2405 fn time_to_live() {
2406 // The following `Vec`s will hold actual and expected notifications.
2407 let actual = Arc::new(Mutex::new(Vec::new()));
2408 let mut expected = Vec::new();
2409
2410 // Create an eviction listener.
2411 let a1 = Arc::clone(&actual);
2412 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
2413
2414 let (clock, mock) = Clock::mock();
2415
2416 // Create a cache with the eviction listener.
2417 let mut cache = Cache::builder()
2418 .max_capacity(100)
2419 .time_to_live(Duration::from_secs(10))
2420 .eviction_listener(listener)
2421 .clock(clock)
2422 .build();
2423 cache.reconfigure_for_testing();
2424
2425 // Make the cache exterior immutable.
2426 let cache = cache;
2427
2428 cache.insert("a", "alice");
2429 cache.run_pending_tasks();
2430
2431 mock.increment(Duration::from_secs(5)); // 5 secs from the start.
2432 cache.run_pending_tasks();
2433
2434 assert_eq!(cache.get(&"a"), Some("alice"));
2435 assert!(cache.contains_key(&"a"));
2436
2437 mock.increment(Duration::from_secs(5)); // 10 secs.
2438 expected.push((Arc::new("a"), "alice", RemovalCause::Expired));
2439 assert_eq!(cache.get(&"a"), None);
2440 assert!(!cache.contains_key(&"a"));
2441
2442 assert_eq!(cache.iter().count(), 0);
2443
2444 cache.run_pending_tasks();
2445 assert!(cache.is_table_empty());
2446
2447 cache.insert("b", "bob");
2448 cache.run_pending_tasks();
2449
2450 assert_eq!(cache.entry_count(), 1);
2451
2452 mock.increment(Duration::from_secs(5)); // 15 secs.
2453 cache.run_pending_tasks();
2454
2455 assert_eq!(cache.get(&"b"), Some("bob"));
2456 assert!(cache.contains_key(&"b"));
2457 assert_eq!(cache.entry_count(), 1);
2458
2459 cache.insert("b", "bill");
2460 expected.push((Arc::new("b"), "bob", RemovalCause::Replaced));
2461 cache.run_pending_tasks();
2462
2463 mock.increment(Duration::from_secs(5)); // 20 secs
2464 cache.run_pending_tasks();
2465
2466 assert_eq!(cache.get(&"b"), Some("bill"));
2467 assert!(cache.contains_key(&"b"));
2468 assert_eq!(cache.entry_count(), 1);
2469
2470 mock.increment(Duration::from_secs(5)); // 25 secs
2471 expected.push((Arc::new("b"), "bill", RemovalCause::Expired));
2472
2473 assert_eq!(cache.get(&"a"), None);
2474 assert_eq!(cache.get(&"b"), None);
2475 assert!(!cache.contains_key(&"a"));
2476 assert!(!cache.contains_key(&"b"));
2477
2478 assert_eq!(cache.iter().count(), 0);
2479
2480 cache.run_pending_tasks();
2481 assert!(cache.is_table_empty());
2482
2483 verify_notification_vec(&cache, actual, &expected);
2484 }
2485
2486 #[test]
2487 fn time_to_idle() {
2488 // The following `Vec`s will hold actual and expected notifications.
2489 let actual = Arc::new(Mutex::new(Vec::new()));
2490 let mut expected = Vec::new();
2491
2492 // Create an eviction listener.
2493 let a1 = Arc::clone(&actual);
2494 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
2495
2496 let (clock, mock) = Clock::mock();
2497
2498 // Create a cache with the eviction listener.
2499 let mut cache = Cache::builder()
2500 .max_capacity(100)
2501 .time_to_idle(Duration::from_secs(10))
2502 .eviction_listener(listener)
2503 .clock(clock)
2504 .build();
2505 cache.reconfigure_for_testing();
2506
2507 // Make the cache exterior immutable.
2508 let cache = cache;
2509
2510 cache.insert("a", "alice");
2511 cache.run_pending_tasks();
2512
2513 mock.increment(Duration::from_secs(5)); // 5 secs from the start.
2514 cache.run_pending_tasks();
2515
2516 assert_eq!(cache.get(&"a"), Some("alice"));
2517
2518 mock.increment(Duration::from_secs(5)); // 10 secs.
2519 cache.run_pending_tasks();
2520
2521 cache.insert("b", "bob");
2522 cache.run_pending_tasks();
2523
2524 assert_eq!(cache.entry_count(), 2);
2525
2526 mock.increment(Duration::from_secs(2)); // 12 secs.
2527 cache.run_pending_tasks();
2528
2529 // contains_key does not reset the idle timer for the key.
2530 assert!(cache.contains_key(&"a"));
2531 assert!(cache.contains_key(&"b"));
2532 cache.run_pending_tasks();
2533
2534 assert_eq!(cache.entry_count(), 2);
2535
2536 mock.increment(Duration::from_secs(3)); // 15 secs.
2537 expected.push((Arc::new("a"), "alice", RemovalCause::Expired));
2538
2539 assert_eq!(cache.get(&"a"), None);
2540 assert_eq!(cache.get(&"b"), Some("bob"));
2541 assert!(!cache.contains_key(&"a"));
2542 assert!(cache.contains_key(&"b"));
2543
2544 assert_eq!(cache.iter().count(), 1);
2545
2546 cache.run_pending_tasks();
2547 assert_eq!(cache.entry_count(), 1);
2548
2549 mock.increment(Duration::from_secs(10)); // 25 secs
2550 expected.push((Arc::new("b"), "bob", RemovalCause::Expired));
2551
2552 assert_eq!(cache.get(&"a"), None);
2553 assert_eq!(cache.get(&"b"), None);
2554 assert!(!cache.contains_key(&"a"));
2555 assert!(!cache.contains_key(&"b"));
2556
2557 assert_eq!(cache.iter().count(), 0);
2558
2559 cache.run_pending_tasks();
2560 assert!(cache.is_table_empty());
2561
2562 verify_notification_vec(&cache, actual, &expected);
2563 }
2564
2565 // https://github.com/moka-rs/moka/issues/359
2566 #[test]
2567 fn ensure_access_time_is_updated_immediately_after_read() {
2568 let (clock, mock) = Clock::mock();
2569 let mut cache = Cache::builder()
2570 .max_capacity(10)
2571 .time_to_idle(Duration::from_secs(5))
2572 .clock(clock)
2573 .build();
2574 cache.reconfigure_for_testing();
2575
2576 // Make the cache exterior immutable.
2577 let cache = cache;
2578
2579 cache.insert(1, 1);
2580
2581 mock.increment(Duration::from_secs(4));
2582 assert_eq!(cache.get(&1), Some(1));
2583
2584 mock.increment(Duration::from_secs(2));
2585 assert_eq!(cache.get(&1), Some(1));
2586 cache.run_pending_tasks();
2587 assert_eq!(cache.get(&1), Some(1));
2588 }
2589
2590 #[test]
2591 fn time_to_live_by_expiry_type() {
2592 // Define an expiry type.
2593 struct MyExpiry {
2594 counters: Arc<ExpiryCallCounters>,
2595 }
2596
2597 impl MyExpiry {
2598 fn new(counters: Arc<ExpiryCallCounters>) -> Self {
2599 Self { counters }
2600 }
2601 }
2602
2603 impl Expiry<&str, &str> for MyExpiry {
2604 fn expire_after_create(
2605 &self,
2606 _key: &&str,
2607 _value: &&str,
2608 _current_time: StdInstant,
2609 ) -> Option<Duration> {
2610 self.counters.incl_actual_creations();
2611 Some(Duration::from_secs(10))
2612 }
2613
2614 fn expire_after_update(
2615 &self,
2616 _key: &&str,
2617 _value: &&str,
2618 _current_time: StdInstant,
2619 _current_duration: Option<Duration>,
2620 ) -> Option<Duration> {
2621 self.counters.incl_actual_updates();
2622 Some(Duration::from_secs(10))
2623 }
2624 }
2625
2626 // The following `Vec`s will hold actual and expected notifications.
2627 let actual = Arc::new(Mutex::new(Vec::new()));
2628 let mut expected = Vec::new();
2629
2630 // Create expiry counters and the expiry.
2631 let expiry_counters = Arc::new(ExpiryCallCounters::default());
2632 let expiry = MyExpiry::new(Arc::clone(&expiry_counters));
2633
2634 // Create an eviction listener.
2635 let a1 = Arc::clone(&actual);
2636 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
2637
2638 let (clock, mock) = Clock::mock();
2639
2640 // Create a cache with the eviction listener.
2641 let mut cache = Cache::builder()
2642 .max_capacity(100)
2643 .expire_after(expiry)
2644 .eviction_listener(listener)
2645 .clock(clock)
2646 .build();
2647 cache.reconfigure_for_testing();
2648
2649 // Make the cache exterior immutable.
2650 let cache = cache;
2651
2652 cache.insert("a", "alice");
2653 expiry_counters.incl_expected_creations();
2654 cache.run_pending_tasks();
2655
2656 mock.increment(Duration::from_secs(5)); // 5 secs from the start.
2657 cache.run_pending_tasks();
2658
2659 assert_eq!(cache.get(&"a"), Some("alice"));
2660 assert!(cache.contains_key(&"a"));
2661
2662 mock.increment(Duration::from_secs(5)); // 10 secs.
2663 expected.push((Arc::new("a"), "alice", RemovalCause::Expired));
2664 assert_eq!(cache.get(&"a"), None);
2665 assert!(!cache.contains_key(&"a"));
2666
2667 assert_eq!(cache.iter().count(), 0);
2668
2669 cache.run_pending_tasks();
2670 assert!(cache.is_table_empty());
2671
2672 cache.insert("b", "bob");
2673 expiry_counters.incl_expected_creations();
2674 cache.run_pending_tasks();
2675
2676 assert_eq!(cache.entry_count(), 1);
2677
2678 mock.increment(Duration::from_secs(5)); // 15 secs.
2679 cache.run_pending_tasks();
2680
2681 assert_eq!(cache.get(&"b"), Some("bob"));
2682 assert!(cache.contains_key(&"b"));
2683 assert_eq!(cache.entry_count(), 1);
2684
2685 cache.insert("b", "bill");
2686 expected.push((Arc::new("b"), "bob", RemovalCause::Replaced));
2687 expiry_counters.incl_expected_updates();
2688 cache.run_pending_tasks();
2689
2690 mock.increment(Duration::from_secs(5)); // 20 secs
2691 cache.run_pending_tasks();
2692
2693 assert_eq!(cache.get(&"b"), Some("bill"));
2694 assert!(cache.contains_key(&"b"));
2695 assert_eq!(cache.entry_count(), 1);
2696
2697 mock.increment(Duration::from_secs(5)); // 25 secs
2698 expected.push((Arc::new("b"), "bill", RemovalCause::Expired));
2699
2700 assert_eq!(cache.get(&"a"), None);
2701 assert_eq!(cache.get(&"b"), None);
2702 assert!(!cache.contains_key(&"a"));
2703 assert!(!cache.contains_key(&"b"));
2704
2705 assert_eq!(cache.iter().count(), 0);
2706
2707 cache.run_pending_tasks();
2708 assert!(cache.is_table_empty());
2709
2710 expiry_counters.verify();
2711 verify_notification_vec(&cache, actual, &expected);
2712 }
2713
2714 #[test]
2715 fn time_to_idle_by_expiry_type() {
2716 // Define an expiry type.
2717 struct MyExpiry {
2718 counters: Arc<ExpiryCallCounters>,
2719 }
2720
2721 impl MyExpiry {
2722 fn new(counters: Arc<ExpiryCallCounters>) -> Self {
2723 Self { counters }
2724 }
2725 }
2726
2727 impl Expiry<&str, &str> for MyExpiry {
2728 fn expire_after_read(
2729 &self,
2730 _key: &&str,
2731 _value: &&str,
2732 _current_time: StdInstant,
2733 _current_duration: Option<Duration>,
2734 _last_modified_at: StdInstant,
2735 ) -> Option<Duration> {
2736 self.counters.incl_actual_reads();
2737 Some(Duration::from_secs(10))
2738 }
2739 }
2740
2741 // The following `Vec`s will hold actual and expected notifications.
2742 let actual = Arc::new(Mutex::new(Vec::new()));
2743 let mut expected = Vec::new();
2744
2745 // Create expiry counters and the expiry.
2746 let expiry_counters = Arc::new(ExpiryCallCounters::default());
2747 let expiry = MyExpiry::new(Arc::clone(&expiry_counters));
2748
2749 // Create an eviction listener.
2750 let a1 = Arc::clone(&actual);
2751 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
2752
2753 let (clock, mock) = Clock::mock();
2754
2755 // Create a cache with the eviction listener.
2756 let mut cache = Cache::builder()
2757 .max_capacity(100)
2758 .expire_after(expiry)
2759 .eviction_listener(listener)
2760 .clock(clock)
2761 .build();
2762 cache.reconfigure_for_testing();
2763
2764 // Make the cache exterior immutable.
2765 let cache = cache;
2766
2767 cache.insert("a", "alice");
2768 cache.run_pending_tasks();
2769
2770 mock.increment(Duration::from_secs(5)); // 5 secs from the start.
2771 cache.run_pending_tasks();
2772
2773 assert_eq!(cache.get(&"a"), Some("alice"));
2774 expiry_counters.incl_expected_reads();
2775
2776 mock.increment(Duration::from_secs(5)); // 10 secs.
2777 cache.run_pending_tasks();
2778
2779 cache.insert("b", "bob");
2780 cache.run_pending_tasks();
2781
2782 assert_eq!(cache.entry_count(), 2);
2783
2784 mock.increment(Duration::from_secs(2)); // 12 secs.
2785 cache.run_pending_tasks();
2786
2787 // contains_key does not reset the idle timer for the key.
2788 assert!(cache.contains_key(&"a"));
2789 assert!(cache.contains_key(&"b"));
2790 cache.run_pending_tasks();
2791
2792 assert_eq!(cache.entry_count(), 2);
2793
2794 mock.increment(Duration::from_secs(3)); // 15 secs.
2795 expected.push((Arc::new("a"), "alice", RemovalCause::Expired));
2796
2797 assert_eq!(cache.get(&"a"), None);
2798 assert_eq!(cache.get(&"b"), Some("bob"));
2799 expiry_counters.incl_expected_reads();
2800 assert!(!cache.contains_key(&"a"));
2801 assert!(cache.contains_key(&"b"));
2802
2803 assert_eq!(cache.iter().count(), 1);
2804
2805 cache.run_pending_tasks();
2806 assert_eq!(cache.entry_count(), 1);
2807
2808 mock.increment(Duration::from_secs(10)); // 25 secs
2809 expected.push((Arc::new("b"), "bob", RemovalCause::Expired));
2810
2811 assert_eq!(cache.get(&"a"), None);
2812 assert_eq!(cache.get(&"b"), None);
2813 assert!(!cache.contains_key(&"a"));
2814 assert!(!cache.contains_key(&"b"));
2815
2816 assert_eq!(cache.iter().count(), 0);
2817
2818 cache.run_pending_tasks();
2819 assert!(cache.is_table_empty());
2820
2821 expiry_counters.verify();
2822 verify_notification_vec(&cache, actual, &expected);
2823 }
2824
2825 /// Verify that the `Expiry::expire_after_read()` method is called in `get_with`
2826 /// only when the key was already present in the cache.
2827 #[test]
2828 fn test_expiry_using_get_with() {
2829 // Define an expiry type, which always return `None`.
2830 struct NoExpiry {
2831 counters: Arc<ExpiryCallCounters>,
2832 }
2833
2834 impl NoExpiry {
2835 fn new(counters: Arc<ExpiryCallCounters>) -> Self {
2836 Self { counters }
2837 }
2838 }
2839
2840 impl Expiry<&str, &str> for NoExpiry {
2841 fn expire_after_create(
2842 &self,
2843 _key: &&str,
2844 _value: &&str,
2845 _current_time: StdInstant,
2846 ) -> Option<Duration> {
2847 self.counters.incl_actual_creations();
2848 None
2849 }
2850
2851 fn expire_after_read(
2852 &self,
2853 _key: &&str,
2854 _value: &&str,
2855 _current_time: StdInstant,
2856 _current_duration: Option<Duration>,
2857 _last_modified_at: StdInstant,
2858 ) -> Option<Duration> {
2859 self.counters.incl_actual_reads();
2860 None
2861 }
2862
2863 fn expire_after_update(
2864 &self,
2865 _key: &&str,
2866 _value: &&str,
2867 _current_time: StdInstant,
2868 _current_duration: Option<Duration>,
2869 ) -> Option<Duration> {
2870 unreachable!("The `expire_after_update()` method should not be called.");
2871 }
2872 }
2873
2874 // Create expiry counters and the expiry.
2875 let expiry_counters = Arc::new(ExpiryCallCounters::default());
2876 let expiry = NoExpiry::new(Arc::clone(&expiry_counters));
2877
2878 // Create a cache with the expiry and eviction listener.
2879 let mut cache = Cache::builder()
2880 .max_capacity(100)
2881 .expire_after(expiry)
2882 .build();
2883 cache.reconfigure_for_testing();
2884
2885 // Make the cache exterior immutable.
2886 let cache = cache;
2887
2888 // The key is not present.
2889 cache.get_with("a", || "alice");
2890 expiry_counters.incl_expected_creations();
2891 cache.run_pending_tasks();
2892
2893 // The key is present.
2894 cache.get_with("a", || "alex");
2895 expiry_counters.incl_expected_reads();
2896 cache.run_pending_tasks();
2897
2898 // The key is not present.
2899 cache.invalidate("a");
2900 cache.get_with("a", || "amanda");
2901 expiry_counters.incl_expected_creations();
2902 cache.run_pending_tasks();
2903
2904 expiry_counters.verify();
2905 }
2906
2907 /// Test that returning `None` from `expire_after_update` properly clears
2908 /// expiration for an already expired entry.
2909 ///
2910 /// Expected behavior: After `expire_after_update` returns `None`, the entry
2911 /// should become accessible via `get()`.
2912 #[test]
2913 fn expire_after_update_none_on_expired_entry() {
2914 use std::sync::atomic::{AtomicBool, Ordering};
2915
2916 // A flag to control whether the entry should expire immediately
2917 let should_expire = Arc::new(AtomicBool::new(true));
2918
2919 struct TestExpiry {
2920 should_expire: Arc<AtomicBool>,
2921 }
2922
2923 impl crate::Expiry<String, String> for TestExpiry {
2924 fn expire_after_create(
2925 &self,
2926 _key: &String,
2927 _value: &String,
2928 _current_time: StdInstant,
2929 ) -> Option<Duration> {
2930 if self.should_expire.load(Ordering::SeqCst) {
2931 // Expire immediately
2932 Some(Duration::ZERO)
2933 } else {
2934 // No expiration
2935 None
2936 }
2937 }
2938
2939 fn expire_after_update(
2940 &self,
2941 _key: &String,
2942 _value: &String,
2943 _current_time: StdInstant,
2944 _duration_until_expiry: Option<Duration>,
2945 ) -> Option<Duration> {
2946 if self.should_expire.load(Ordering::SeqCst) {
2947 Some(Duration::ZERO)
2948 } else {
2949 // According to docs, None means "no expiration"
2950 // This should make the entry accessible again
2951 None
2952 }
2953 }
2954 }
2955
2956 let expiry = TestExpiry {
2957 should_expire: Arc::clone(&should_expire),
2958 };
2959
2960 let cache: Cache<String, String> = Cache::builder()
2961 .max_capacity(100)
2962 .expire_after(expiry)
2963 .build();
2964
2965 let key = "test_key".to_string();
2966
2967 // Insert entry that expires immediately
2968 cache.insert(key.clone(), "first_value".to_string());
2969 cache.run_pending_tasks();
2970
2971 // Entry should exist but be expired
2972 assert_eq!(cache.entry_count(), 1, "Entry should exist in cache");
2973 assert_eq!(
2974 cache.get(&key),
2975 None,
2976 "Entry should not be accessible (expired)"
2977 );
2978 cache.run_pending_tasks();
2979
2980 // Now update the entry to NOT expire (expire_after_update returns None)
2981 should_expire.store(false, Ordering::SeqCst);
2982 cache.insert(key.clone(), "second_value".to_string());
2983 cache.run_pending_tasks();
2984
2985 // The entry should now be accessible since we returned None
2986 // (meaning "no expiration") from expire_after_update
2987 assert_eq!(cache.entry_count(), 1, "Entry should exist in cache");
2988
2989 // Returning None from expire_after_update should clear the expiration.
2990 let result = cache.get(&key);
2991 assert_eq!(
2992 result,
2993 Some("second_value".to_string()),
2994 "Entry should be accessible after clearing expiration"
2995 );
2996 }
2997
2998 // https://github.com/moka-rs/moka/issues/345
2999 #[test]
3000 fn test_race_between_updating_entry_and_processing_its_write_ops() {
3001 let (clock, mock) = Clock::mock();
3002 let cache = Cache::builder()
3003 .max_capacity(2)
3004 .time_to_idle(Duration::from_secs(1))
3005 .clock(clock)
3006 .build();
3007
3008 cache.insert("a", "alice");
3009 cache.insert("b", "bob");
3010 cache.insert("c", "cathy"); // c1
3011 mock.increment(Duration::from_secs(2));
3012
3013 // The following `insert` will do the followings:
3014 // 1. Replaces current "c" (c1) in the concurrent hash table (cht).
3015 // 2. Runs the pending tasks implicitly.
3016 // (1) "a" will be admitted.
3017 // (2) "b" will be admitted.
3018 // (3) c1 will be evicted by size constraint.
3019 // (4) "a" will be evicted due to expiration.
3020 // (5) "b" will be evicted due to expiration.
3021 // 3. Send its `WriteOp` log to the channel.
3022 cache.insert("c", "cindy"); // c2
3023
3024 // Remove "c" (c2) from the cht.
3025 assert_eq!(cache.remove(&"c"), Some("cindy")); // c-remove
3026
3027 mock.increment(Duration::from_secs(2));
3028
3029 // The following `run_pending_tasks` will do the followings:
3030 // 1. Admits "c" (c2) to the cache. (Create a node in the LRU deque)
3031 // 2. Because of c-remove, removes c2's node from the LRU deque.
3032 cache.run_pending_tasks();
3033 assert_eq!(cache.entry_count(), 0);
3034 }
3035
3036 #[test]
3037 fn test_race_between_recreating_entry_and_processing_its_write_ops() {
3038 let cache = Cache::builder().max_capacity(2).build();
3039
3040 cache.insert('a', "a");
3041 cache.insert('b', "b");
3042 cache.run_pending_tasks();
3043
3044 cache.insert('c', "c1"); // (a) `EntryInfo` 1, gen: 1
3045 assert!(cache.remove(&'a').is_some()); // (b)
3046 assert!(cache.remove(&'b').is_some()); // (c)
3047 assert!(cache.remove(&'c').is_some()); // (d) `EntryInfo` 1, gen: 2
3048 cache.insert('c', "c2"); // (e) `EntryInfo` 2, gen: 1
3049
3050 // Now the `write_op_ch` channel contains the following `WriteOp`s:
3051 //
3052 // - 0: (a) insert "c1" (`EntryInfo` 1, gen: 1)
3053 // - 1: (b) remove "a"
3054 // - 2: (c) remove "b"
3055 // - 3: (d) remove "c1" (`EntryInfo` 1, gen: 2)
3056 // - 4: (e) insert "c2" (`EntryInfo` 2, gen: 1)
3057 //
3058 // 0 for "c1" is going to be rejected because the cache is full. Let's ensure
3059 // processing 0 must not remove "c2" from the concurrent hash table. (Their
3060 // gen are the same, but `EntryInfo`s are different)
3061 cache.run_pending_tasks();
3062 assert_eq!(cache.get(&'c'), Some("c2"));
3063 }
3064
3065 #[test]
3066 fn test_iter() {
3067 const NUM_KEYS: usize = 50;
3068
3069 fn make_value(key: usize) -> String {
3070 format!("val: {key}")
3071 }
3072
3073 let cache = Cache::builder()
3074 .max_capacity(100)
3075 .time_to_idle(Duration::from_secs(10))
3076 .build();
3077
3078 for key in 0..NUM_KEYS {
3079 cache.insert(key, make_value(key));
3080 }
3081
3082 let mut key_set = std::collections::HashSet::new();
3083
3084 for (key, value) in &cache {
3085 assert_eq!(value, make_value(*key));
3086
3087 key_set.insert(*key);
3088 }
3089
3090 // Ensure there are no missing or duplicate keys in the iteration.
3091 assert_eq!(key_set.len(), NUM_KEYS);
3092 }
3093
3094 /// Runs 16 threads at the same time and ensures no deadlock occurs.
3095 ///
3096 /// - Eight of the threads will update key-values in the cache.
3097 /// - Eight others will iterate the cache.
3098 ///
3099 #[test]
3100 fn test_iter_multi_threads() {
3101 use std::collections::HashSet;
3102
3103 const NUM_KEYS: usize = 1024;
3104 const NUM_THREADS: usize = 16;
3105
3106 fn make_value(key: usize) -> String {
3107 format!("val: {key}")
3108 }
3109
3110 let cache = Cache::builder()
3111 .max_capacity(2048)
3112 .time_to_idle(Duration::from_secs(10))
3113 .build();
3114
3115 // Initialize the cache.
3116 for key in 0..NUM_KEYS {
3117 cache.insert(key, make_value(key));
3118 }
3119
3120 let rw_lock = Arc::new(std::sync::RwLock::<()>::default());
3121 let write_lock = rw_lock.write().unwrap();
3122
3123 // https://rust-lang.github.io/rust-clippy/master/index.html#needless_collect
3124 #[allow(clippy::needless_collect)]
3125 let handles = (0..NUM_THREADS)
3126 .map(|n| {
3127 let cache = cache.clone();
3128 let rw_lock = Arc::clone(&rw_lock);
3129
3130 if n % 2 == 0 {
3131 // This thread will update the cache.
3132 std::thread::spawn(move || {
3133 let read_lock = rw_lock.read().unwrap();
3134 for key in 0..NUM_KEYS {
3135 // TODO: Update keys in a random order?
3136 cache.insert(key, make_value(key));
3137 }
3138 std::mem::drop(read_lock);
3139 })
3140 } else {
3141 // This thread will iterate the cache.
3142 std::thread::spawn(move || {
3143 let read_lock = rw_lock.read().unwrap();
3144 let mut key_set = HashSet::new();
3145 for (key, value) in &cache {
3146 assert_eq!(value, make_value(*key));
3147 key_set.insert(*key);
3148 }
3149 // Ensure there are no missing or duplicate keys in the iteration.
3150 assert_eq!(key_set.len(), NUM_KEYS);
3151 std::mem::drop(read_lock);
3152 })
3153 }
3154 })
3155 .collect::<Vec<_>>();
3156
3157 // Let these threads to run by releasing the write lock.
3158 std::mem::drop(write_lock);
3159
3160 handles.into_iter().for_each(|h| h.join().expect("Failed"));
3161
3162 // Ensure there are no missing or duplicate keys in the iteration.
3163 let key_set = cache.iter().map(|(k, _v)| *k).collect::<HashSet<_>>();
3164 assert_eq!(key_set.len(), NUM_KEYS);
3165 }
3166
3167 #[test]
3168 fn get_with() {
3169 use std::thread::{sleep, spawn};
3170
3171 let cache = Cache::new(100);
3172 const KEY: u32 = 0;
3173
3174 // This test will run five threads:
3175 //
3176 // Thread1 will be the first thread to call `get_with` for a key, so its init
3177 // closure will be evaluated and then a &str value "thread1" will be inserted
3178 // to the cache.
3179 let thread1 = {
3180 let cache1 = cache.clone();
3181 spawn(move || {
3182 // Call `get_with` immediately.
3183 let v = cache1.get_with(KEY, || {
3184 // Wait for 300 ms and return a &str value.
3185 sleep(Duration::from_millis(300));
3186 "thread1"
3187 });
3188 assert_eq!(v, "thread1");
3189 })
3190 };
3191
3192 // Thread2 will be the second thread to call `get_with` for the same key, so
3193 // its init closure will not be evaluated. Once thread1's init closure
3194 // finishes, it will get the value inserted by thread1's init closure.
3195 let thread2 = {
3196 let cache2 = cache.clone();
3197 spawn(move || {
3198 // Wait for 100 ms before calling `get_with`.
3199 sleep(Duration::from_millis(100));
3200 let v = cache2.get_with(KEY, || unreachable!());
3201 assert_eq!(v, "thread1");
3202 })
3203 };
3204
3205 // Thread3 will be the third thread to call `get_with` for the same key. By
3206 // the time it calls, thread1's init closure should have finished already and
3207 // the value should be already inserted to the cache. So its init closure
3208 // will not be evaluated and will get the value insert by thread1's init
3209 // closure immediately.
3210 let thread3 = {
3211 let cache3 = cache.clone();
3212 spawn(move || {
3213 // Wait for 400 ms before calling `get_with`.
3214 sleep(Duration::from_millis(400));
3215 let v = cache3.get_with(KEY, || unreachable!());
3216 assert_eq!(v, "thread1");
3217 })
3218 };
3219
3220 // Thread4 will call `get` for the same key. It will call when thread1's init
3221 // closure is still running, so it will get none for the key.
3222 let thread4 = {
3223 let cache4 = cache.clone();
3224 spawn(move || {
3225 // Wait for 200 ms before calling `get`.
3226 sleep(Duration::from_millis(200));
3227 let maybe_v = cache4.get(&KEY);
3228 assert!(maybe_v.is_none());
3229 })
3230 };
3231
3232 // Thread5 will call `get` for the same key. It will call after thread1's init
3233 // closure finished, so it will get the value insert by thread1's init closure.
3234 let thread5 = {
3235 let cache5 = cache.clone();
3236 spawn(move || {
3237 // Wait for 400 ms before calling `get`.
3238 sleep(Duration::from_millis(400));
3239 let maybe_v = cache5.get(&KEY);
3240 assert_eq!(maybe_v, Some("thread1"));
3241 })
3242 };
3243
3244 for t in [thread1, thread2, thread3, thread4, thread5] {
3245 t.join().expect("Failed to join");
3246 }
3247
3248 assert!(cache.is_waiter_map_empty());
3249 }
3250
3251 #[test]
3252 fn get_with_by_ref() {
3253 use std::thread::{sleep, spawn};
3254
3255 let cache = Cache::new(100);
3256 const KEY: &u32 = &0;
3257
3258 // This test will run five threads:
3259 //
3260 // Thread1 will be the first thread to call `get_with_by_ref` for a key, so
3261 // its init closure will be evaluated and then a &str value "thread1" will be
3262 // inserted to the cache.
3263 let thread1 = {
3264 let cache1 = cache.clone();
3265 spawn(move || {
3266 // Call `get_with_by_ref` immediately.
3267 let v = cache1.get_with_by_ref(KEY, || {
3268 // Wait for 300 ms and return a &str value.
3269 sleep(Duration::from_millis(300));
3270 "thread1"
3271 });
3272 assert_eq!(v, "thread1");
3273 })
3274 };
3275
3276 // Thread2 will be the second thread to call `get_with_by_ref` for the same
3277 // key, so its init closure will not be evaluated. Once thread1's init
3278 // closure finishes, it will get the value inserted by thread1's init
3279 // closure.
3280 let thread2 = {
3281 let cache2 = cache.clone();
3282 spawn(move || {
3283 // Wait for 100 ms before calling `get_with_by_ref`.
3284 sleep(Duration::from_millis(100));
3285 let v = cache2.get_with_by_ref(KEY, || unreachable!());
3286 assert_eq!(v, "thread1");
3287 })
3288 };
3289
3290 // Thread3 will be the third thread to call `get_with_by_ref` for the same
3291 // key. By the time it calls, thread1's init closure should have finished
3292 // already and the value should be already inserted to the cache. So its init
3293 // closure will not be evaluated and will get the value insert by thread1's
3294 // init closure immediately.
3295 let thread3 = {
3296 let cache3 = cache.clone();
3297 spawn(move || {
3298 // Wait for 400 ms before calling `get_with_by_ref`.
3299 sleep(Duration::from_millis(400));
3300 let v = cache3.get_with_by_ref(KEY, || unreachable!());
3301 assert_eq!(v, "thread1");
3302 })
3303 };
3304
3305 // Thread4 will call `get` for the same key. It will call when thread1's init
3306 // closure is still running, so it will get none for the key.
3307 let thread4 = {
3308 let cache4 = cache.clone();
3309 spawn(move || {
3310 // Wait for 200 ms before calling `get`.
3311 sleep(Duration::from_millis(200));
3312 let maybe_v = cache4.get(KEY);
3313 assert!(maybe_v.is_none());
3314 })
3315 };
3316
3317 // Thread5 will call `get` for the same key. It will call after thread1's init
3318 // closure finished, so it will get the value insert by thread1's init closure.
3319 let thread5 = {
3320 let cache5 = cache.clone();
3321 spawn(move || {
3322 // Wait for 400 ms before calling `get`.
3323 sleep(Duration::from_millis(400));
3324 let maybe_v = cache5.get(KEY);
3325 assert_eq!(maybe_v, Some("thread1"));
3326 })
3327 };
3328
3329 for t in [thread1, thread2, thread3, thread4, thread5] {
3330 t.join().expect("Failed to join");
3331 }
3332
3333 assert!(cache.is_waiter_map_empty());
3334 }
3335
3336 #[test]
3337 fn entry_or_insert_with_if() {
3338 use std::thread::{sleep, spawn};
3339
3340 let cache = Cache::new(100);
3341 const KEY: u32 = 0;
3342
3343 // This test will run seven threads:
3344 //
3345 // Thread1 will be the first thread to call `or_insert_with_if` for a key, so
3346 // its init closure will be evaluated and then a &str value "thread1" will be
3347 // inserted to the cache.
3348 let thread1 = {
3349 let cache1 = cache.clone();
3350 spawn(move || {
3351 // Call `get_with` immediately.
3352 let entry = cache1.entry(KEY).or_insert_with_if(
3353 || {
3354 // Wait for 300 ms and return a &str value.
3355 sleep(Duration::from_millis(300));
3356 "thread1"
3357 },
3358 |_v| unreachable!(),
3359 );
3360 // Entry should be fresh because our async block should have been
3361 // evaluated.
3362 assert!(entry.is_fresh());
3363 assert_eq!(entry.into_value(), "thread1");
3364 })
3365 };
3366
3367 // Thread2 will be the second thread to call `or_insert_with_if` for the same
3368 // key, so its init closure will not be evaluated. Once thread1's init
3369 // closure finishes, it will get the value inserted by thread1's init
3370 // closure.
3371 let thread2 = {
3372 let cache2 = cache.clone();
3373 spawn(move || {
3374 // Wait for 100 ms before calling `get_with`.
3375 sleep(Duration::from_millis(100));
3376 let entry = cache2
3377 .entry(KEY)
3378 .or_insert_with_if(|| unreachable!(), |_v| unreachable!());
3379 // Entry should not be fresh because thread1's async block should have
3380 // been evaluated instead of ours.
3381 assert!(!entry.is_fresh());
3382 assert_eq!(entry.into_value(), "thread1");
3383 })
3384 };
3385
3386 // Thread3 will be the third thread to call `or_insert_with_if` for the same
3387 // key. By the time it calls, thread1's init closure should have finished
3388 // already and the value should be already inserted to the cache. Also
3389 // thread3's `replace_if` closure returns `false`. So its init closure will
3390 // not be evaluated and will get the value inserted by thread1's init closure
3391 // immediately.
3392 let thread3 = {
3393 let cache3 = cache.clone();
3394 spawn(move || {
3395 // Wait for 350 ms before calling `or_insert_with_if`.
3396 sleep(Duration::from_millis(350));
3397 let entry = cache3.entry(KEY).or_insert_with_if(
3398 || unreachable!(),
3399 |v| {
3400 assert_eq!(v, &"thread1");
3401 false
3402 },
3403 );
3404 assert!(!entry.is_fresh());
3405 assert_eq!(entry.into_value(), "thread1");
3406 })
3407 };
3408
3409 // Thread4 will be the fourth thread to call `or_insert_with_if` for the same
3410 // key. The value should have been already inserted to the cache by thread1.
3411 // However thread4's `replace_if` closure returns `true`. So its init closure
3412 // will be evaluated to replace the current value.
3413 let thread4 = {
3414 let cache4 = cache.clone();
3415 spawn(move || {
3416 // Wait for 400 ms before calling `or_insert_with_if`.
3417 sleep(Duration::from_millis(400));
3418 let entry = cache4.entry(KEY).or_insert_with_if(
3419 || "thread4",
3420 |v| {
3421 assert_eq!(v, &"thread1");
3422 true
3423 },
3424 );
3425 assert!(entry.is_fresh());
3426 assert_eq!(entry.into_value(), "thread4");
3427 })
3428 };
3429
3430 // Thread5 will call `get` for the same key. It will call when thread1's init
3431 // closure is still running, so it will get none for the key.
3432 let thread5 = {
3433 let cache5 = cache.clone();
3434 spawn(move || {
3435 // Wait for 200 ms before calling `get`.
3436 sleep(Duration::from_millis(200));
3437 let maybe_v = cache5.get(&KEY);
3438 assert!(maybe_v.is_none());
3439 })
3440 };
3441
3442 // Thread6 will call `get` for the same key. It will call when thread1's init
3443 // closure is still running, so it will get none for the key.
3444 let thread6 = {
3445 let cache6 = cache.clone();
3446 spawn(move || {
3447 // Wait for 350 ms before calling `get`.
3448 sleep(Duration::from_millis(350));
3449 let maybe_v = cache6.get(&KEY);
3450 assert_eq!(maybe_v, Some("thread1"));
3451 })
3452 };
3453
3454 // Thread7 will call `get` for the same key. It will call after thread1's init
3455 // closure finished, so it will get the value insert by thread1's init closure.
3456 let thread7 = {
3457 let cache7 = cache.clone();
3458 spawn(move || {
3459 // Wait for 450 ms before calling `get`.
3460 sleep(Duration::from_millis(450));
3461 let maybe_v = cache7.get(&KEY);
3462 assert_eq!(maybe_v, Some("thread4"));
3463 })
3464 };
3465
3466 for t in [
3467 thread1, thread2, thread3, thread4, thread5, thread6, thread7,
3468 ] {
3469 t.join().expect("Failed to join");
3470 }
3471
3472 assert!(cache.is_waiter_map_empty());
3473 }
3474
3475 #[test]
3476 fn entry_by_ref_or_insert_with_if() {
3477 use std::thread::{sleep, spawn};
3478
3479 let cache: Cache<u32, &str> = Cache::new(100);
3480 const KEY: &u32 = &0;
3481
3482 // This test will run seven threads:
3483 //
3484 // Thread1 will be the first thread to call `or_insert_with_if` for a key, so
3485 // its init closure will be evaluated and then a &str value "thread1" will be
3486 // inserted to the cache.
3487 let thread1 = {
3488 let cache1 = cache.clone();
3489 spawn(move || {
3490 // Call `get_with` immediately.
3491 let v = cache1
3492 .entry_by_ref(KEY)
3493 .or_insert_with_if(
3494 || {
3495 // Wait for 300 ms and return a &str value.
3496 sleep(Duration::from_millis(300));
3497 "thread1"
3498 },
3499 |_v| unreachable!(),
3500 )
3501 .into_value();
3502 assert_eq!(v, "thread1");
3503 })
3504 };
3505
3506 // Thread2 will be the second thread to call `or_insert_with_if` for the same
3507 // key, so its init closure will not be evaluated. Once thread1's init
3508 // closure finishes, it will get the value inserted by thread1's init
3509 // closure.
3510 let thread2 = {
3511 let cache2 = cache.clone();
3512 spawn(move || {
3513 // Wait for 100 ms before calling `get_with`.
3514 sleep(Duration::from_millis(100));
3515 let v = cache2
3516 .entry_by_ref(KEY)
3517 .or_insert_with_if(|| unreachable!(), |_v| unreachable!())
3518 .into_value();
3519 assert_eq!(v, "thread1");
3520 })
3521 };
3522
3523 // Thread3 will be the third thread to call `or_insert_with_if` for the same
3524 // key. By the time it calls, thread1's init closure should have finished
3525 // already and the value should be already inserted to the cache. Also
3526 // thread3's `replace_if` closure returns `false`. So its init closure will
3527 // not be evaluated and will get the value inserted by thread1's init closure
3528 // immediately.
3529 let thread3 = {
3530 let cache3 = cache.clone();
3531 spawn(move || {
3532 // Wait for 350 ms before calling `or_insert_with_if`.
3533 sleep(Duration::from_millis(350));
3534 let v = cache3
3535 .entry_by_ref(KEY)
3536 .or_insert_with_if(
3537 || unreachable!(),
3538 |v| {
3539 assert_eq!(v, &"thread1");
3540 false
3541 },
3542 )
3543 .into_value();
3544 assert_eq!(v, "thread1");
3545 })
3546 };
3547
3548 // Thread4 will be the fourth thread to call `or_insert_with_if` for the same
3549 // key. The value should have been already inserted to the cache by
3550 // thread1. However thread4's `replace_if` closure returns `true`. So its
3551 // init closure will be evaluated to replace the current value.
3552 let thread4 = {
3553 let cache4 = cache.clone();
3554 spawn(move || {
3555 // Wait for 400 ms before calling `or_insert_with_if`.
3556 sleep(Duration::from_millis(400));
3557 let v = cache4
3558 .entry_by_ref(KEY)
3559 .or_insert_with_if(
3560 || "thread4",
3561 |v| {
3562 assert_eq!(v, &"thread1");
3563 true
3564 },
3565 )
3566 .into_value();
3567 assert_eq!(v, "thread4");
3568 })
3569 };
3570
3571 // Thread5 will call `get` for the same key. It will call when thread1's init
3572 // closure is still running, so it will get none for the key.
3573 let thread5 = {
3574 let cache5 = cache.clone();
3575 spawn(move || {
3576 // Wait for 200 ms before calling `get`.
3577 sleep(Duration::from_millis(200));
3578 let maybe_v = cache5.get(KEY);
3579 assert!(maybe_v.is_none());
3580 })
3581 };
3582
3583 // Thread6 will call `get` for the same key. It will call when thread1's init
3584 // closure is still running, so it will get none for the key.
3585 let thread6 = {
3586 let cache6 = cache.clone();
3587 spawn(move || {
3588 // Wait for 350 ms before calling `get`.
3589 sleep(Duration::from_millis(350));
3590 let maybe_v = cache6.get(KEY);
3591 assert_eq!(maybe_v, Some("thread1"));
3592 })
3593 };
3594
3595 // Thread7 will call `get` for the same key. It will call after thread1's init
3596 // closure finished, so it will get the value insert by thread1's init closure.
3597 let thread7 = {
3598 let cache7 = cache.clone();
3599 spawn(move || {
3600 // Wait for 450 ms before calling `get`.
3601 sleep(Duration::from_millis(450));
3602 let maybe_v = cache7.get(KEY);
3603 assert_eq!(maybe_v, Some("thread4"));
3604 })
3605 };
3606
3607 for t in [
3608 thread1, thread2, thread3, thread4, thread5, thread6, thread7,
3609 ] {
3610 t.join().expect("Failed to join");
3611 }
3612
3613 assert!(cache.is_waiter_map_empty());
3614 }
3615
3616 #[test]
3617 fn try_get_with() {
3618 use std::{
3619 sync::Arc,
3620 thread::{sleep, spawn},
3621 };
3622
3623 // Note that MyError does not implement std::error::Error trait like
3624 // anyhow::Error.
3625 #[derive(Debug)]
3626 pub struct MyError(#[allow(dead_code)] String);
3627
3628 type MyResult<T> = Result<T, Arc<MyError>>;
3629
3630 let cache = Cache::new(100);
3631 const KEY: u32 = 0;
3632
3633 // This test will run eight threads:
3634 //
3635 // Thread1 will be the first thread to call `try_get_with` for a key, so its
3636 // init closure will be evaluated and then an error will be returned. Nothing
3637 // will be inserted to the cache.
3638 let thread1 = {
3639 let cache1 = cache.clone();
3640 spawn(move || {
3641 // Call `try_get_with` immediately.
3642 let v = cache1.try_get_with(KEY, || {
3643 // Wait for 300 ms and return an error.
3644 sleep(Duration::from_millis(300));
3645 Err(MyError("thread1 error".into()))
3646 });
3647 assert!(v.is_err());
3648 })
3649 };
3650
3651 // Thread2 will be the second thread to call `try_get_with` for the same key,
3652 // so its init closure will not be evaluated. Once thread1's init closure
3653 // finishes, it will get the same error value returned by thread1's init
3654 // closure.
3655 let thread2 = {
3656 let cache2 = cache.clone();
3657 spawn(move || {
3658 // Wait for 100 ms before calling `try_get_with`.
3659 sleep(Duration::from_millis(100));
3660 let v: MyResult<_> = cache2.try_get_with(KEY, || unreachable!());
3661 assert!(v.is_err());
3662 })
3663 };
3664
3665 // Thread3 will be the third thread to call `get_with` for the same key. By
3666 // the time it calls, thread1's init closure should have finished already,
3667 // but the key still does not exist in the cache. So its init closure will be
3668 // evaluated and then an okay &str value will be returned. That value will be
3669 // inserted to the cache.
3670 let thread3 = {
3671 let cache3 = cache.clone();
3672 spawn(move || {
3673 // Wait for 400 ms before calling `try_get_with`.
3674 sleep(Duration::from_millis(400));
3675 let v: MyResult<_> = cache3.try_get_with(KEY, || {
3676 // Wait for 300 ms and return an Ok(&str) value.
3677 sleep(Duration::from_millis(300));
3678 Ok("thread3")
3679 });
3680 assert_eq!(v.unwrap(), "thread3");
3681 })
3682 };
3683
3684 // thread4 will be the fourth thread to call `try_get_with` for the same
3685 // key. So its init closure will not be evaluated. Once thread3's init
3686 // closure finishes, it will get the same okay &str value.
3687 let thread4 = {
3688 let cache4 = cache.clone();
3689 spawn(move || {
3690 // Wait for 500 ms before calling `try_get_with`.
3691 sleep(Duration::from_millis(500));
3692 let v: MyResult<_> = cache4.try_get_with(KEY, || unreachable!());
3693 assert_eq!(v.unwrap(), "thread3");
3694 })
3695 };
3696
3697 // Thread5 will be the fifth thread to call `try_get_with` for the same
3698 // key. So its init closure will not be evaluated. By the time it calls,
3699 // thread3's init closure should have finished already, so its init closure
3700 // will not be evaluated and will get the value insert by thread3's init
3701 // closure immediately.
3702 let thread5 = {
3703 let cache5 = cache.clone();
3704 spawn(move || {
3705 // Wait for 800 ms before calling `try_get_with`.
3706 sleep(Duration::from_millis(800));
3707 let v: MyResult<_> = cache5.try_get_with(KEY, || unreachable!());
3708 assert_eq!(v.unwrap(), "thread3");
3709 })
3710 };
3711
3712 // Thread6 will call `get` for the same key. It will call when thread1's init
3713 // closure is still running, so it will get none for the key.
3714 let thread6 = {
3715 let cache6 = cache.clone();
3716 spawn(move || {
3717 // Wait for 200 ms before calling `get`.
3718 sleep(Duration::from_millis(200));
3719 let maybe_v = cache6.get(&KEY);
3720 assert!(maybe_v.is_none());
3721 })
3722 };
3723
3724 // Thread7 will call `get` for the same key. It will call after thread1's init
3725 // closure finished with an error. So it will get none for the key.
3726 let thread7 = {
3727 let cache7 = cache.clone();
3728 spawn(move || {
3729 // Wait for 400 ms before calling `get`.
3730 sleep(Duration::from_millis(400));
3731 let maybe_v = cache7.get(&KEY);
3732 assert!(maybe_v.is_none());
3733 })
3734 };
3735
3736 // Thread8 will call `get` for the same key. It will call after thread3's init
3737 // closure finished, so it will get the value insert by thread3's init closure.
3738 let thread8 = {
3739 let cache8 = cache.clone();
3740 spawn(move || {
3741 // Wait for 800 ms before calling `get`.
3742 sleep(Duration::from_millis(800));
3743 let maybe_v = cache8.get(&KEY);
3744 assert_eq!(maybe_v, Some("thread3"));
3745 })
3746 };
3747
3748 for t in [
3749 thread1, thread2, thread3, thread4, thread5, thread6, thread7, thread8,
3750 ] {
3751 t.join().expect("Failed to join");
3752 }
3753
3754 assert!(cache.is_waiter_map_empty());
3755 }
3756
3757 #[test]
3758 fn try_get_with_by_ref() {
3759 use std::{
3760 sync::Arc,
3761 thread::{sleep, spawn},
3762 };
3763
3764 // Note that MyError does not implement std::error::Error trait like
3765 // anyhow::Error.
3766 #[derive(Debug)]
3767 pub struct MyError(#[allow(dead_code)] String);
3768
3769 type MyResult<T> = Result<T, Arc<MyError>>;
3770
3771 let cache = Cache::new(100);
3772 const KEY: &u32 = &0;
3773
3774 // This test will run eight threads:
3775 //
3776 // Thread1 will be the first thread to call `try_get_with_by_ref` for a key,
3777 // so its init closure will be evaluated and then an error will be returned.
3778 // Nothing will be inserted to the cache.
3779 let thread1 = {
3780 let cache1 = cache.clone();
3781 spawn(move || {
3782 // Call `try_get_with_by_ref` immediately.
3783 let v = cache1.try_get_with_by_ref(KEY, || {
3784 // Wait for 300 ms and return an error.
3785 sleep(Duration::from_millis(300));
3786 Err(MyError("thread1 error".into()))
3787 });
3788 assert!(v.is_err());
3789 })
3790 };
3791
3792 // Thread2 will be the second thread to call `try_get_with_by_ref` for the
3793 // same key, so its init closure will not be evaluated. Once thread1's init
3794 // closure finishes, it will get the same error value returned by thread1's
3795 // init closure.
3796 let thread2 = {
3797 let cache2 = cache.clone();
3798 spawn(move || {
3799 // Wait for 100 ms before calling `try_get_with_by_ref`.
3800 sleep(Duration::from_millis(100));
3801 let v: MyResult<_> = cache2.try_get_with_by_ref(KEY, || unreachable!());
3802 assert!(v.is_err());
3803 })
3804 };
3805
3806 // Thread3 will be the third thread to call `get_with` for the same key. By
3807 // the time it calls, thread1's init closure should have finished already,
3808 // but the key still does not exist in the cache. So its init closure will be
3809 // evaluated and then an okay &str value will be returned. That value will be
3810 // inserted to the cache.
3811 let thread3 = {
3812 let cache3 = cache.clone();
3813 spawn(move || {
3814 // Wait for 400 ms before calling `try_get_with_by_ref`.
3815 sleep(Duration::from_millis(400));
3816 let v: MyResult<_> = cache3.try_get_with_by_ref(KEY, || {
3817 // Wait for 300 ms and return an Ok(&str) value.
3818 sleep(Duration::from_millis(300));
3819 Ok("thread3")
3820 });
3821 assert_eq!(v.unwrap(), "thread3");
3822 })
3823 };
3824
3825 // thread4 will be the fourth thread to call `try_get_with_by_ref` for the
3826 // same key. So its init closure will not be evaluated. Once thread3's init
3827 // closure finishes, it will get the same okay &str value.
3828 let thread4 = {
3829 let cache4 = cache.clone();
3830 spawn(move || {
3831 // Wait for 500 ms before calling `try_get_with_by_ref`.
3832 sleep(Duration::from_millis(500));
3833 let v: MyResult<_> = cache4.try_get_with_by_ref(KEY, || unreachable!());
3834 assert_eq!(v.unwrap(), "thread3");
3835 })
3836 };
3837
3838 // Thread5 will be the fifth thread to call `try_get_with_by_ref` for the
3839 // same key. So its init closure will not be evaluated. By the time it calls,
3840 // thread3's init closure should have finished already, so its init closure
3841 // will not be evaluated and will get the value insert by thread3's init
3842 // closure immediately.
3843 let thread5 = {
3844 let cache5 = cache.clone();
3845 spawn(move || {
3846 // Wait for 800 ms before calling `try_get_with_by_ref`.
3847 sleep(Duration::from_millis(800));
3848 let v: MyResult<_> = cache5.try_get_with_by_ref(KEY, || unreachable!());
3849 assert_eq!(v.unwrap(), "thread3");
3850 })
3851 };
3852
3853 // Thread6 will call `get` for the same key. It will call when thread1's init
3854 // closure is still running, so it will get none for the key.
3855 let thread6 = {
3856 let cache6 = cache.clone();
3857 spawn(move || {
3858 // Wait for 200 ms before calling `get`.
3859 sleep(Duration::from_millis(200));
3860 let maybe_v = cache6.get(KEY);
3861 assert!(maybe_v.is_none());
3862 })
3863 };
3864
3865 // Thread7 will call `get` for the same key. It will call after thread1's init
3866 // closure finished with an error. So it will get none for the key.
3867 let thread7 = {
3868 let cache7 = cache.clone();
3869 spawn(move || {
3870 // Wait for 400 ms before calling `get`.
3871 sleep(Duration::from_millis(400));
3872 let maybe_v = cache7.get(KEY);
3873 assert!(maybe_v.is_none());
3874 })
3875 };
3876
3877 // Thread8 will call `get` for the same key. It will call after thread3's init
3878 // closure finished, so it will get the value insert by thread3's init closure.
3879 let thread8 = {
3880 let cache8 = cache.clone();
3881 spawn(move || {
3882 // Wait for 800 ms before calling `get`.
3883 sleep(Duration::from_millis(800));
3884 let maybe_v = cache8.get(KEY);
3885 assert_eq!(maybe_v, Some("thread3"));
3886 })
3887 };
3888
3889 for t in [
3890 thread1, thread2, thread3, thread4, thread5, thread6, thread7, thread8,
3891 ] {
3892 t.join().expect("Failed to join");
3893 }
3894
3895 assert!(cache.is_waiter_map_empty());
3896 }
3897
3898 #[test]
3899 fn optionally_get_with() {
3900 use std::thread::{sleep, spawn};
3901
3902 let cache = Cache::new(100);
3903 const KEY: u32 = 0;
3904
3905 // This test will run eight threads:
3906 //
3907 // Thread1 will be the first thread to call `optionally_get_with` for a key,
3908 // so its init closure will be evaluated and then an error will be returned.
3909 // Nothing will be inserted to the cache.
3910 let thread1 = {
3911 let cache1 = cache.clone();
3912 spawn(move || {
3913 // Call `optionally_get_with` immediately.
3914 let v = cache1.optionally_get_with(KEY, || {
3915 // Wait for 300 ms and return an error.
3916 sleep(Duration::from_millis(300));
3917 None
3918 });
3919 assert!(v.is_none());
3920 })
3921 };
3922
3923 // Thread2 will be the second thread to call `optionally_get_with` for the
3924 // same key, so its init closure will not be evaluated. Once thread1's init
3925 // closure finishes, it will get the same error value returned by thread1's
3926 // init closure.
3927 let thread2 = {
3928 let cache2 = cache.clone();
3929 spawn(move || {
3930 // Wait for 100 ms before calling `optionally_get_with`.
3931 sleep(Duration::from_millis(100));
3932 let v = cache2.optionally_get_with(KEY, || unreachable!());
3933 assert!(v.is_none());
3934 })
3935 };
3936
3937 // Thread3 will be the third thread to call `get_with` for the same key. By
3938 // the time it calls, thread1's init closure should have finished already,
3939 // but the key still does not exist in the cache. So its init closure will be
3940 // evaluated and then an okay &str value will be returned. That value will be
3941 // inserted to the cache.
3942 let thread3 = {
3943 let cache3 = cache.clone();
3944 spawn(move || {
3945 // Wait for 400 ms before calling `optionally_get_with`.
3946 sleep(Duration::from_millis(400));
3947 let v = cache3.optionally_get_with(KEY, || {
3948 // Wait for 300 ms and return an Ok(&str) value.
3949 sleep(Duration::from_millis(300));
3950 Some("thread3")
3951 });
3952 assert_eq!(v.unwrap(), "thread3");
3953 })
3954 };
3955
3956 // thread4 will be the fourth thread to call `optionally_get_with` for the
3957 // same key. So its init closure will not be evaluated. Once thread3's init
3958 // closure finishes, it will get the same okay &str value.
3959 let thread4 = {
3960 let cache4 = cache.clone();
3961 spawn(move || {
3962 // Wait for 500 ms before calling `optionally_get_with`.
3963 sleep(Duration::from_millis(500));
3964 let v = cache4.optionally_get_with(KEY, || unreachable!());
3965 assert_eq!(v.unwrap(), "thread3");
3966 })
3967 };
3968
3969 // Thread5 will be the fifth thread to call `optionally_get_with` for the
3970 // same key. So its init closure will not be evaluated. By the time it calls,
3971 // thread3's init closure should have finished already, so its init closure
3972 // will not be evaluated and will get the value insert by thread3's init
3973 // closure immediately.
3974 let thread5 = {
3975 let cache5 = cache.clone();
3976 spawn(move || {
3977 // Wait for 800 ms before calling `optionally_get_with`.
3978 sleep(Duration::from_millis(800));
3979 let v = cache5.optionally_get_with(KEY, || unreachable!());
3980 assert_eq!(v.unwrap(), "thread3");
3981 })
3982 };
3983
3984 // Thread6 will call `get` for the same key. It will call when thread1's init
3985 // closure is still running, so it will get none for the key.
3986 let thread6 = {
3987 let cache6 = cache.clone();
3988 spawn(move || {
3989 // Wait for 200 ms before calling `get`.
3990 sleep(Duration::from_millis(200));
3991 let maybe_v = cache6.get(&KEY);
3992 assert!(maybe_v.is_none());
3993 })
3994 };
3995
3996 // Thread7 will call `get` for the same key. It will call after thread1's init
3997 // closure finished with an error. So it will get none for the key.
3998 let thread7 = {
3999 let cache7 = cache.clone();
4000 spawn(move || {
4001 // Wait for 400 ms before calling `get`.
4002 sleep(Duration::from_millis(400));
4003 let maybe_v = cache7.get(&KEY);
4004 assert!(maybe_v.is_none());
4005 })
4006 };
4007
4008 // Thread8 will call `get` for the same key. It will call after thread3's init
4009 // closure finished, so it will get the value insert by thread3's init closure.
4010 let thread8 = {
4011 let cache8 = cache.clone();
4012 spawn(move || {
4013 // Wait for 800 ms before calling `get`.
4014 sleep(Duration::from_millis(800));
4015 let maybe_v = cache8.get(&KEY);
4016 assert_eq!(maybe_v, Some("thread3"));
4017 })
4018 };
4019
4020 for t in [
4021 thread1, thread2, thread3, thread4, thread5, thread6, thread7, thread8,
4022 ] {
4023 t.join().expect("Failed to join");
4024 }
4025
4026 assert!(cache.is_waiter_map_empty());
4027 }
4028
4029 #[test]
4030 fn optionally_get_with_by_ref() {
4031 use std::thread::{sleep, spawn};
4032
4033 let cache = Cache::new(100);
4034 const KEY: &u32 = &0;
4035
4036 // This test will run eight threads:
4037 //
4038 // Thread1 will be the first thread to call `optionally_get_with_by_ref` for
4039 // a key, so its init closure will be evaluated and then an error will be
4040 // returned. Nothing will be inserted to the cache.
4041 let thread1 = {
4042 let cache1 = cache.clone();
4043 spawn(move || {
4044 // Call `optionally_get_with_by_ref` immediately.
4045 let v = cache1.optionally_get_with_by_ref(KEY, || {
4046 // Wait for 300 ms and return an error.
4047 sleep(Duration::from_millis(300));
4048 None
4049 });
4050 assert!(v.is_none());
4051 })
4052 };
4053
4054 // Thread2 will be the second thread to call `optionally_get_with_by_ref` for
4055 // the same key, so its init closure will not be evaluated. Once thread1's
4056 // init closure finishes, it will get the same error value returned by
4057 // thread1's init closure.
4058 let thread2 = {
4059 let cache2 = cache.clone();
4060 spawn(move || {
4061 // Wait for 100 ms before calling `optionally_get_with_by_ref`.
4062 sleep(Duration::from_millis(100));
4063 let v = cache2.optionally_get_with_by_ref(KEY, || unreachable!());
4064 assert!(v.is_none());
4065 })
4066 };
4067
4068 // Thread3 will be the third thread to call `get_with` for the same key. By
4069 // the time it calls, thread1's init closure should have finished already,
4070 // but the key still does not exist in the cache. So its init closure will be
4071 // evaluated and then an okay &str value will be returned. That value will be
4072 // inserted to the cache.
4073 let thread3 = {
4074 let cache3 = cache.clone();
4075 spawn(move || {
4076 // Wait for 400 ms before calling `optionally_get_with_by_ref`.
4077 sleep(Duration::from_millis(400));
4078 let v = cache3.optionally_get_with_by_ref(KEY, || {
4079 // Wait for 300 ms and return an Ok(&str) value.
4080 sleep(Duration::from_millis(300));
4081 Some("thread3")
4082 });
4083 assert_eq!(v.unwrap(), "thread3");
4084 })
4085 };
4086
4087 // thread4 will be the fourth thread to call `optionally_get_with_by_ref` for
4088 // the same key. So its init closure will not be evaluated. Once thread3's
4089 // init closure finishes, it will get the same okay &str value.
4090 let thread4 = {
4091 let cache4 = cache.clone();
4092 spawn(move || {
4093 // Wait for 500 ms before calling `optionally_get_with_by_ref`.
4094 sleep(Duration::from_millis(500));
4095 let v = cache4.optionally_get_with_by_ref(KEY, || unreachable!());
4096 assert_eq!(v.unwrap(), "thread3");
4097 })
4098 };
4099
4100 // Thread5 will be the fifth thread to call `optionally_get_with_by_ref` for
4101 // the same key. So its init closure will not be evaluated. By the time it
4102 // calls, thread3's init closure should have finished already, so its init
4103 // closure will not be evaluated and will get the value insert by thread3's
4104 // init closure immediately.
4105 let thread5 = {
4106 let cache5 = cache.clone();
4107 spawn(move || {
4108 // Wait for 800 ms before calling `optionally_get_with_by_ref`.
4109 sleep(Duration::from_millis(800));
4110 let v = cache5.optionally_get_with_by_ref(KEY, || unreachable!());
4111 assert_eq!(v.unwrap(), "thread3");
4112 })
4113 };
4114
4115 // Thread6 will call `get` for the same key. It will call when thread1's init
4116 // closure is still running, so it will get none for the key.
4117 let thread6 = {
4118 let cache6 = cache.clone();
4119 spawn(move || {
4120 // Wait for 200 ms before calling `get`.
4121 sleep(Duration::from_millis(200));
4122 let maybe_v = cache6.get(KEY);
4123 assert!(maybe_v.is_none());
4124 })
4125 };
4126
4127 // Thread7 will call `get` for the same key. It will call after thread1's init
4128 // closure finished with an error. So it will get none for the key.
4129 let thread7 = {
4130 let cache7 = cache.clone();
4131 spawn(move || {
4132 // Wait for 400 ms before calling `get`.
4133 sleep(Duration::from_millis(400));
4134 let maybe_v = cache7.get(KEY);
4135 assert!(maybe_v.is_none());
4136 })
4137 };
4138
4139 // Thread8 will call `get` for the same key. It will call after thread3's init
4140 // closure finished, so it will get the value insert by thread3's init closure.
4141 let thread8 = {
4142 let cache8 = cache.clone();
4143 spawn(move || {
4144 // Wait for 800 ms before calling `get`.
4145 sleep(Duration::from_millis(800));
4146 let maybe_v = cache8.get(KEY);
4147 assert_eq!(maybe_v, Some("thread3"));
4148 })
4149 };
4150
4151 for t in [
4152 thread1, thread2, thread3, thread4, thread5, thread6, thread7, thread8,
4153 ] {
4154 t.join().expect("Failed to join");
4155 }
4156
4157 assert!(cache.is_waiter_map_empty());
4158 }
4159
4160 #[test]
4161 fn upsert_with() {
4162 use std::thread::{sleep, spawn};
4163
4164 let cache = Cache::new(100);
4165 const KEY: u32 = 0;
4166
4167 // Spawn three threads to call `and_upsert_with` for the same key and each
4168 // task increments the current value by 1. Ensure the key-level lock is
4169 // working by verifying the value is 3 after all threads finish.
4170 //
4171 // | | thread 1 | thread 2 | thread 3 |
4172 // |--------|----------|----------|----------|
4173 // | 0 ms | get none | | |
4174 // | 100 ms | | blocked | |
4175 // | 200 ms | insert 1 | | |
4176 // | | | get 1 | |
4177 // | 300 ms | | | blocked |
4178 // | 400 ms | | insert 2 | |
4179 // | | | | get 2 |
4180 // | 500 ms | | | insert 3 |
4181
4182 let thread1 = {
4183 let cache1 = cache.clone();
4184 spawn(move || {
4185 cache1.entry(KEY).and_upsert_with(|maybe_entry| {
4186 sleep(Duration::from_millis(200));
4187 assert!(maybe_entry.is_none());
4188 1
4189 })
4190 })
4191 };
4192
4193 let thread2 = {
4194 let cache2 = cache.clone();
4195 spawn(move || {
4196 sleep(Duration::from_millis(100));
4197 cache2.entry_by_ref(&KEY).and_upsert_with(|maybe_entry| {
4198 sleep(Duration::from_millis(200));
4199 let entry = maybe_entry.expect("The entry should exist");
4200 entry.into_value() + 1
4201 })
4202 })
4203 };
4204
4205 let thread3 = {
4206 let cache3 = cache.clone();
4207 spawn(move || {
4208 sleep(Duration::from_millis(300));
4209 cache3.entry_by_ref(&KEY).and_upsert_with(|maybe_entry| {
4210 sleep(Duration::from_millis(100));
4211 let entry = maybe_entry.expect("The entry should exist");
4212 entry.into_value() + 1
4213 })
4214 })
4215 };
4216
4217 let ent1 = thread1.join().expect("Thread 1 should finish");
4218 let ent2 = thread2.join().expect("Thread 2 should finish");
4219 let ent3 = thread3.join().expect("Thread 3 should finish");
4220 assert_eq!(ent1.into_value(), 1);
4221 assert_eq!(ent2.into_value(), 2);
4222 assert_eq!(ent3.into_value(), 3);
4223
4224 assert_eq!(cache.get(&KEY), Some(3));
4225
4226 assert!(cache.is_waiter_map_empty());
4227 }
4228
4229 #[test]
4230 fn compute_with() {
4231 use crate::ops::compute;
4232 use std::{
4233 sync::RwLock,
4234 thread::{sleep, spawn},
4235 };
4236
4237 let cache = Cache::new(100);
4238 const KEY: u32 = 0;
4239
4240 // Spawn six threads to call `and_compute_with` for the same key. Ensure the
4241 // key-level lock is working by verifying the value after all threads finish.
4242 //
4243 // | | thread 1 | thread 2 | thread 3 | thread 4 | thread 5 | thread 6 |
4244 // |---------|------------|---------------|------------|----------|------------|----------|
4245 // | 0 ms | get none | | | | | |
4246 // | 100 ms | | blocked | | | | |
4247 // | 200 ms | insert [1] | | | | | |
4248 // | | | get [1] | | | | |
4249 // | 300 ms | | | blocked | | | |
4250 // | 400 ms | | insert [1, 2] | | | | |
4251 // | | | | get [1, 2] | | | |
4252 // | 500 ms | | | | blocked | | |
4253 // | 600 ms | | | remove | | | |
4254 // | | | | | get none | | |
4255 // | 700 ms | | | | | blocked | |
4256 // | 800 ms | | | | nop | | |
4257 // | | | | | | get none | |
4258 // | 900 ms | | | | | | blocked |
4259 // | 1000 ms | | | | | insert [5] | |
4260 // | | | | | | | get [5] |
4261 // | 1100 ms | | | | | | nop |
4262
4263 let thread1 = {
4264 let cache1 = cache.clone();
4265 spawn(move || {
4266 cache1.entry(KEY).and_compute_with(|maybe_entry| {
4267 sleep(Duration::from_millis(200));
4268 assert!(maybe_entry.is_none());
4269 compute::Op::Put(Arc::new(RwLock::new(vec![1])))
4270 })
4271 })
4272 };
4273
4274 let thread2 = {
4275 let cache2 = cache.clone();
4276 spawn(move || {
4277 sleep(Duration::from_millis(100));
4278 cache2.entry_by_ref(&KEY).and_compute_with(|maybe_entry| {
4279 let entry = maybe_entry.expect("The entry should exist");
4280 let value = entry.into_value();
4281 assert_eq!(*value.read().unwrap(), vec![1]);
4282 sleep(Duration::from_millis(200));
4283 value.write().unwrap().push(2);
4284 compute::Op::Put(value)
4285 })
4286 })
4287 };
4288
4289 let thread3 = {
4290 let cache3 = cache.clone();
4291 spawn(move || {
4292 sleep(Duration::from_millis(300));
4293 cache3.entry(KEY).and_compute_with(|maybe_entry| {
4294 let entry = maybe_entry.expect("The entry should exist");
4295 let value = entry.into_value();
4296 assert_eq!(*value.read().unwrap(), vec![1, 2]);
4297 sleep(Duration::from_millis(200));
4298 compute::Op::Remove
4299 })
4300 })
4301 };
4302
4303 let thread4 = {
4304 let cache4 = cache.clone();
4305 spawn(move || {
4306 sleep(Duration::from_millis(500));
4307 cache4.entry(KEY).and_compute_with(|maybe_entry| {
4308 assert!(maybe_entry.is_none());
4309 sleep(Duration::from_millis(200));
4310 compute::Op::Nop
4311 })
4312 })
4313 };
4314
4315 let thread5 = {
4316 let cache5 = cache.clone();
4317 spawn(move || {
4318 sleep(Duration::from_millis(700));
4319 cache5.entry_by_ref(&KEY).and_compute_with(|maybe_entry| {
4320 assert!(maybe_entry.is_none());
4321 sleep(Duration::from_millis(200));
4322 compute::Op::Put(Arc::new(RwLock::new(vec![5])))
4323 })
4324 })
4325 };
4326
4327 let thread6 = {
4328 let cache6 = cache.clone();
4329 spawn(move || {
4330 sleep(Duration::from_millis(900));
4331 cache6.entry_by_ref(&KEY).and_compute_with(|maybe_entry| {
4332 let entry = maybe_entry.expect("The entry should exist");
4333 let value = entry.into_value();
4334 assert_eq!(*value.read().unwrap(), vec![5]);
4335 sleep(Duration::from_millis(100));
4336 compute::Op::Nop
4337 })
4338 })
4339 };
4340
4341 let res1 = thread1.join().expect("Thread 1 should finish");
4342 let res2 = thread2.join().expect("Thread 2 should finish");
4343 let res3 = thread3.join().expect("Thread 3 should finish");
4344 let res4 = thread4.join().expect("Thread 4 should finish");
4345 let res5 = thread5.join().expect("Thread 5 should finish");
4346 let res6 = thread6.join().expect("Thread 6 should finish");
4347
4348 let compute::CompResult::Inserted(entry) = res1 else {
4349 panic!("Expected `Inserted`. Got {res1:?}")
4350 };
4351 assert_eq!(
4352 *entry.into_value().read().unwrap(),
4353 vec![1, 2] // The same Vec was modified by task2.
4354 );
4355
4356 let compute::CompResult::ReplacedWith(entry) = res2 else {
4357 panic!("Expected `ReplacedWith`. Got {res2:?}")
4358 };
4359 assert_eq!(*entry.into_value().read().unwrap(), vec![1, 2]);
4360
4361 let compute::CompResult::Removed(entry) = res3 else {
4362 panic!("Expected `Removed`. Got {res3:?}")
4363 };
4364 assert_eq!(*entry.into_value().read().unwrap(), vec![1, 2]);
4365
4366 let compute::CompResult::StillNone(key) = res4 else {
4367 panic!("Expected `StillNone`. Got {res4:?}")
4368 };
4369 assert_eq!(*key, KEY);
4370
4371 let compute::CompResult::Inserted(entry) = res5 else {
4372 panic!("Expected `Inserted`. Got {res5:?}")
4373 };
4374 assert_eq!(*entry.into_value().read().unwrap(), vec![5]);
4375
4376 let compute::CompResult::Unchanged(entry) = res6 else {
4377 panic!("Expected `Unchanged`. Got {res6:?}")
4378 };
4379 assert_eq!(*entry.into_value().read().unwrap(), vec![5]);
4380
4381 assert!(cache.is_waiter_map_empty());
4382 }
4383
4384 #[test]
4385 fn try_compute_with() {
4386 use crate::ops::compute;
4387 use std::{
4388 sync::RwLock,
4389 thread::{sleep, spawn},
4390 };
4391
4392 let cache: Cache<u32, Arc<RwLock<Vec<i32>>>> = Cache::new(100);
4393 const KEY: u32 = 0;
4394
4395 // Spawn four threads to call `and_try_compute_with` for the same key. Ensure
4396 // the key-level lock is working by verifying the value after all threads
4397 // finish.
4398 //
4399 // | | thread 1 | thread 2 | thread 3 | thread 4 |
4400 // |---------|------------|---------------|------------|------------|
4401 // | 0 ms | get none | | | |
4402 // | 100 ms | | blocked | | |
4403 // | 200 ms | insert [1] | | | |
4404 // | | | get [1] | | |
4405 // | 300 ms | | | blocked | |
4406 // | 400 ms | | insert [1, 2] | | |
4407 // | | | | get [1, 2] | |
4408 // | 500 ms | | | | blocked |
4409 // | 600 ms | | | err | |
4410 // | | | | | get [1, 2] |
4411 // | 700 ms | | | | remove |
4412 //
4413 // This test is shorter than `compute_with` test because this one omits `Nop`
4414 // cases.
4415
4416 let thread1 = {
4417 let cache1 = cache.clone();
4418 spawn(move || {
4419 cache1.entry(KEY).and_try_compute_with(|maybe_entry| {
4420 sleep(Duration::from_millis(200));
4421 assert!(maybe_entry.is_none());
4422 Ok(compute::Op::Put(Arc::new(RwLock::new(vec![1])))) as Result<_, ()>
4423 })
4424 })
4425 };
4426
4427 let thread2 = {
4428 let cache2 = cache.clone();
4429 spawn(move || {
4430 sleep(Duration::from_millis(100));
4431 cache2
4432 .entry_by_ref(&KEY)
4433 .and_try_compute_with(|maybe_entry| {
4434 let entry = maybe_entry.expect("The entry should exist");
4435 let value = entry.into_value();
4436 assert_eq!(*value.read().unwrap(), vec![1]);
4437 sleep(Duration::from_millis(200));
4438 value.write().unwrap().push(2);
4439 Ok(compute::Op::Put(value)) as Result<_, ()>
4440 })
4441 })
4442 };
4443
4444 let thread3 = {
4445 let cache3 = cache.clone();
4446 spawn(move || {
4447 sleep(Duration::from_millis(300));
4448 cache3.entry(KEY).and_try_compute_with(|maybe_entry| {
4449 let entry = maybe_entry.expect("The entry should exist");
4450 let value = entry.into_value();
4451 assert_eq!(*value.read().unwrap(), vec![1, 2]);
4452 sleep(Duration::from_millis(200));
4453 Err(())
4454 })
4455 })
4456 };
4457
4458 let thread4 = {
4459 let cache4 = cache.clone();
4460 spawn(move || {
4461 sleep(Duration::from_millis(500));
4462 cache4.entry(KEY).and_try_compute_with(|maybe_entry| {
4463 let entry = maybe_entry.expect("The entry should exist");
4464 let value = entry.into_value();
4465 assert_eq!(*value.read().unwrap(), vec![1, 2]);
4466 sleep(Duration::from_millis(100));
4467 Ok(compute::Op::Remove) as Result<_, ()>
4468 })
4469 })
4470 };
4471
4472 let res1 = thread1.join().expect("Thread 1 should finish");
4473 let res2 = thread2.join().expect("Thread 2 should finish");
4474 let res3 = thread3.join().expect("Thread 3 should finish");
4475 let res4 = thread4.join().expect("Thread 4 should finish");
4476
4477 let Ok(compute::CompResult::Inserted(entry)) = res1 else {
4478 panic!("Expected `Inserted`. Got {res1:?}")
4479 };
4480 assert_eq!(
4481 *entry.into_value().read().unwrap(),
4482 vec![1, 2] // The same Vec was modified by task2.
4483 );
4484
4485 let Ok(compute::CompResult::ReplacedWith(entry)) = res2 else {
4486 panic!("Expected `ReplacedWith`. Got {res2:?}")
4487 };
4488 assert_eq!(*entry.into_value().read().unwrap(), vec![1, 2]);
4489
4490 assert!(res3.is_err());
4491
4492 let Ok(compute::CompResult::Removed(entry)) = res4 else {
4493 panic!("Expected `Removed`. Got {res4:?}")
4494 };
4495 assert_eq!(
4496 *entry.into_value().read().unwrap(),
4497 vec![1, 2] // Removed value.
4498 );
4499
4500 assert!(cache.is_waiter_map_empty());
4501 }
4502
4503 #[test]
4504 // https://github.com/moka-rs/moka/issues/43
4505 fn handle_panic_in_get_with() {
4506 use std::{sync::Barrier, thread};
4507
4508 let cache = Cache::new(16);
4509 let barrier = Arc::new(Barrier::new(2));
4510 {
4511 let cache_ref = cache.clone();
4512 let barrier_ref = barrier.clone();
4513 thread::spawn(move || {
4514 let _ = cache_ref.get_with(1, || {
4515 barrier_ref.wait();
4516 thread::sleep(Duration::from_millis(50));
4517 panic!("Panic during get_with");
4518 });
4519 });
4520 }
4521
4522 barrier.wait();
4523 assert_eq!(cache.get_with(1, || 5), 5);
4524
4525 assert!(cache.is_waiter_map_empty());
4526 }
4527
4528 #[test]
4529 // https://github.com/moka-rs/moka/issues/43
4530 fn handle_panic_in_try_get_with() {
4531 use std::{sync::Barrier, thread};
4532
4533 let cache = Cache::new(16);
4534 let barrier = Arc::new(Barrier::new(2));
4535 {
4536 let cache_ref = cache.clone();
4537 let barrier_ref = barrier.clone();
4538 thread::spawn(move || {
4539 let _ = cache_ref.try_get_with(1, || {
4540 barrier_ref.wait();
4541 thread::sleep(Duration::from_millis(50));
4542 panic!("Panic during try_get_with");
4543 }) as Result<_, Arc<Infallible>>;
4544 });
4545 }
4546
4547 barrier.wait();
4548 assert_eq!(
4549 cache.try_get_with(1, || Ok(5)) as Result<_, Arc<Infallible>>,
4550 Ok(5)
4551 );
4552
4553 assert!(cache.is_waiter_map_empty());
4554 }
4555
4556 #[test]
4557 fn test_removal_notifications() {
4558 // The following `Vec`s will hold actual and expected notifications.
4559 let actual = Arc::new(Mutex::new(Vec::new()));
4560 let mut expected = Vec::new();
4561
4562 // Create an eviction listener.
4563 let a1 = Arc::clone(&actual);
4564 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
4565
4566 // Create a cache with the eviction listener.
4567 let mut cache = Cache::builder()
4568 .max_capacity(3)
4569 .eviction_listener(listener)
4570 .build();
4571 cache.reconfigure_for_testing();
4572
4573 // Make the cache exterior immutable.
4574 let cache = cache;
4575
4576 cache.insert('a', "alice");
4577 cache.invalidate(&'a');
4578 expected.push((Arc::new('a'), "alice", RemovalCause::Explicit));
4579
4580 cache.run_pending_tasks();
4581 assert_eq!(cache.entry_count(), 0);
4582
4583 cache.insert('b', "bob");
4584 cache.insert('c', "cathy");
4585 cache.insert('d', "david");
4586 cache.run_pending_tasks();
4587 assert_eq!(cache.entry_count(), 3);
4588
4589 // This will be rejected due to the size constraint.
4590 cache.insert('e', "emily");
4591 expected.push((Arc::new('e'), "emily", RemovalCause::Size));
4592 cache.run_pending_tasks();
4593 assert_eq!(cache.entry_count(), 3);
4594
4595 // Raise the popularity of 'e' so it will be accepted next time.
4596 cache.get(&'e');
4597 cache.run_pending_tasks();
4598
4599 // Retry.
4600 cache.insert('e', "eliza");
4601 // and the LRU entry will be evicted.
4602 expected.push((Arc::new('b'), "bob", RemovalCause::Size));
4603 cache.run_pending_tasks();
4604 assert_eq!(cache.entry_count(), 3);
4605
4606 // Replace an existing entry.
4607 cache.insert('d', "dennis");
4608 expected.push((Arc::new('d'), "david", RemovalCause::Replaced));
4609 cache.run_pending_tasks();
4610 assert_eq!(cache.entry_count(), 3);
4611
4612 verify_notification_vec(&cache, actual, &expected);
4613 }
4614
4615 #[test]
4616 fn test_immediate_removal_notifications_with_updates() {
4617 // The following `Vec` will hold actual notifications.
4618 let actual = Arc::new(Mutex::new(Vec::new()));
4619
4620 // Create an eviction listener.
4621 let a1 = Arc::clone(&actual);
4622 let listener = move |k, v, cause| a1.lock().push((k, v, cause));
4623
4624 let (clock, mock) = Clock::mock();
4625
4626 // Create a cache with the eviction listener and also TTL and TTI.
4627 let mut cache = Cache::builder()
4628 .eviction_listener(listener)
4629 .time_to_live(Duration::from_secs(7))
4630 .time_to_idle(Duration::from_secs(5))
4631 .clock(clock)
4632 .build();
4633 cache.reconfigure_for_testing();
4634
4635 // Make the cache exterior immutable.
4636 let cache = cache;
4637
4638 cache.insert("alice", "a0");
4639 cache.run_pending_tasks();
4640
4641 // Now alice (a0) has been expired by the idle timeout (TTI).
4642 mock.increment(Duration::from_secs(6));
4643 assert_eq!(cache.get(&"alice"), None);
4644
4645 // We have not ran sync after the expiration of alice (a0), so it is
4646 // still in the cache.
4647 assert_eq!(cache.entry_count(), 1);
4648
4649 // Re-insert alice with a different value. Since alice (a0) is still
4650 // in the cache, this is actually a replace operation rather than an
4651 // insert operation. We want to verify that the RemovalCause of a0 is
4652 // Expired, not Replaced.
4653 cache.insert("alice", "a1");
4654 {
4655 let mut a = actual.lock();
4656 assert_eq!(a.len(), 1);
4657 assert_eq!(a[0], (Arc::new("alice"), "a0", RemovalCause::Expired));
4658 a.clear();
4659 }
4660
4661 cache.run_pending_tasks();
4662
4663 mock.increment(Duration::from_secs(4));
4664 assert_eq!(cache.get(&"alice"), Some("a1"));
4665 cache.run_pending_tasks();
4666
4667 // Now alice has been expired by time-to-live (TTL).
4668 mock.increment(Duration::from_secs(4));
4669 assert_eq!(cache.get(&"alice"), None);
4670
4671 // But, again, it is still in the cache.
4672 assert_eq!(cache.entry_count(), 1);
4673
4674 // Re-insert alice with a different value and verify that the
4675 // RemovalCause of a1 is Expired (not Replaced).
4676 cache.insert("alice", "a2");
4677 {
4678 let mut a = actual.lock();
4679 assert_eq!(a.len(), 1);
4680 assert_eq!(a[0], (Arc::new("alice"), "a1", RemovalCause::Expired));
4681 a.clear();
4682 }
4683
4684 cache.run_pending_tasks();
4685
4686 assert_eq!(cache.entry_count(), 1);
4687
4688 // Now alice (a2) has been expired by the idle timeout.
4689 mock.increment(Duration::from_secs(6));
4690 assert_eq!(cache.get(&"alice"), None);
4691 assert_eq!(cache.entry_count(), 1);
4692
4693 // This invalidate will internally remove alice (a2).
4694 cache.invalidate(&"alice");
4695 cache.run_pending_tasks();
4696 assert_eq!(cache.entry_count(), 0);
4697
4698 {
4699 let mut a = actual.lock();
4700 assert_eq!(a.len(), 1);
4701 assert_eq!(a[0], (Arc::new("alice"), "a2", RemovalCause::Expired));
4702 a.clear();
4703 }
4704
4705 // Re-insert, and this time, make it expired by the TTL.
4706 cache.insert("alice", "a3");
4707 cache.run_pending_tasks();
4708 mock.increment(Duration::from_secs(4));
4709 assert_eq!(cache.get(&"alice"), Some("a3"));
4710 cache.run_pending_tasks();
4711 mock.increment(Duration::from_secs(4));
4712 assert_eq!(cache.get(&"alice"), None);
4713 assert_eq!(cache.entry_count(), 1);
4714
4715 // This invalidate will internally remove alice (a2).
4716 cache.invalidate(&"alice");
4717 cache.run_pending_tasks();
4718
4719 assert_eq!(cache.entry_count(), 0);
4720
4721 {
4722 let mut a = actual.lock();
4723 assert_eq!(a.len(), 1);
4724 assert_eq!(a[0], (Arc::new("alice"), "a3", RemovalCause::Expired));
4725 a.clear();
4726 }
4727
4728 assert!(cache.key_locks_map_is_empty());
4729 }
4730
4731 // This test ensures the key-level lock for the immediate notification
4732 // delivery mode is working so that the notifications for a given key
4733 // should always be ordered. This is true even if multiple client threads
4734 // try to modify the entries for the key at the same time. (This test will
4735 // run three client threads)
4736 //
4737 // This test is ignored by default. It becomes unstable when run in parallel
4738 // with other tests.
4739 #[test]
4740 #[ignore]
4741 fn test_key_lock_used_by_immediate_removal_notifications() {
4742 use std::thread::{sleep, spawn};
4743
4744 const KEY: &str = "alice";
4745
4746 type Val = &'static str;
4747
4748 #[derive(PartialEq, Eq, Debug)]
4749 enum Event {
4750 Insert(Val),
4751 Invalidate(Val),
4752 BeginNotify(Val, RemovalCause),
4753 EndNotify(Val, RemovalCause),
4754 }
4755
4756 // The following `Vec will hold actual notifications.
4757 let actual = Arc::new(Mutex::new(Vec::new()));
4758
4759 // Create an eviction listener.
4760 // Note that this listener is slow and will take 300 ms to complete.
4761 let a0 = Arc::clone(&actual);
4762 let listener = move |_k, v, cause| {
4763 a0.lock().push(Event::BeginNotify(v, cause));
4764 sleep(Duration::from_millis(300));
4765 a0.lock().push(Event::EndNotify(v, cause));
4766 };
4767
4768 // Create a cache with the eviction listener and also TTL 500 ms.
4769 let mut cache = Cache::builder()
4770 .eviction_listener(listener)
4771 .time_to_live(Duration::from_millis(500))
4772 .build();
4773 cache.reconfigure_for_testing();
4774
4775 // Make the cache exterior immutable.
4776 let cache = cache;
4777
4778 // - Notifications for the same key must not overlap.
4779
4780 // Time Event
4781 // ----- -------------------------------------
4782 // 0000: Insert value a0
4783 // 0500: a0 expired
4784 // 0600: Insert value a1 -> expired a0 (N-A0)
4785 // 0800: Insert value a2 (waiting) (A-A2)
4786 // 0900: N-A0 processed
4787 // A-A2 finished waiting -> replace a1 (N-A1)
4788 // 1100: Invalidate (waiting) (R-A2)
4789 // 1200: N-A1 processed
4790 // R-A2 finished waiting -> explicit a2 (N-A2)
4791 // 1500: N-A2 processed
4792
4793 let expected = vec![
4794 Event::Insert("a0"),
4795 Event::Insert("a1"),
4796 Event::BeginNotify("a0", RemovalCause::Expired),
4797 Event::Insert("a2"),
4798 Event::EndNotify("a0", RemovalCause::Expired),
4799 Event::BeginNotify("a1", RemovalCause::Replaced),
4800 Event::Invalidate("a2"),
4801 Event::EndNotify("a1", RemovalCause::Replaced),
4802 Event::BeginNotify("a2", RemovalCause::Explicit),
4803 Event::EndNotify("a2", RemovalCause::Explicit),
4804 ];
4805
4806 // 0000: Insert value a0
4807 actual.lock().push(Event::Insert("a0"));
4808 cache.insert(KEY, "a0");
4809 // Call `sync` to set the last modified for the KEY immediately so that
4810 // this entry should expire in 1000 ms from now.
4811 cache.run_pending_tasks();
4812
4813 // 0500: Insert value a1 -> expired a0 (N-A0)
4814 let thread1 = {
4815 let a1 = Arc::clone(&actual);
4816 let c1 = cache.clone();
4817 spawn(move || {
4818 sleep(Duration::from_millis(600));
4819 a1.lock().push(Event::Insert("a1"));
4820 c1.insert(KEY, "a1");
4821 })
4822 };
4823
4824 // 0800: Insert value a2 (waiting) (A-A2)
4825 let thread2 = {
4826 let a2 = Arc::clone(&actual);
4827 let c2 = cache.clone();
4828 spawn(move || {
4829 sleep(Duration::from_millis(800));
4830 a2.lock().push(Event::Insert("a2"));
4831 c2.insert(KEY, "a2");
4832 })
4833 };
4834
4835 // 1100: Invalidate (waiting) (R-A2)
4836 let thread3 = {
4837 let a3 = Arc::clone(&actual);
4838 let c3 = cache.clone();
4839 spawn(move || {
4840 sleep(Duration::from_millis(1100));
4841 a3.lock().push(Event::Invalidate("a2"));
4842 c3.invalidate(&KEY);
4843 })
4844 };
4845
4846 for t in [thread1, thread2, thread3] {
4847 t.join().expect("Failed to join");
4848 }
4849
4850 let actual = actual.lock();
4851 assert_eq!(actual.len(), expected.len());
4852
4853 for (i, (actual, expected)) in actual.iter().zip(&expected).enumerate() {
4854 assert_eq!(actual, expected, "expected[{i}]");
4855 }
4856
4857 assert!(cache.key_locks_map_is_empty());
4858 }
4859
4860 // When the eviction listener is not set, calling `run_pending_tasks` once should
4861 // evict all entries that can be removed.
4862 #[test]
4863 fn no_batch_size_limit_on_eviction() {
4864 const MAX_CAPACITY: u64 = 20;
4865
4866 const EVICTION_TIMEOUT: Duration = Duration::from_nanos(0);
4867 const MAX_LOG_SYNC_REPEATS: u32 = 1;
4868 const EVICTION_BATCH_SIZE: u32 = 1;
4869
4870 let hk_conf = HousekeeperConfig::new(
4871 // Timeout should be ignored when the eviction listener is not provided.
4872 Some(EVICTION_TIMEOUT),
4873 Some(MAX_LOG_SYNC_REPEATS),
4874 Some(EVICTION_BATCH_SIZE),
4875 );
4876
4877 // Create a cache with the LRU policy.
4878 let mut cache = Cache::builder()
4879 .max_capacity(MAX_CAPACITY)
4880 .eviction_policy(EvictionPolicy::lru())
4881 .housekeeper_config(hk_conf)
4882 .build();
4883 cache.reconfigure_for_testing();
4884
4885 // Make the cache exterior immutable.
4886 let cache = cache;
4887
4888 // Fill the cache.
4889 for i in 0..MAX_CAPACITY {
4890 let v = format!("v{i}");
4891 cache.insert(i, v)
4892 }
4893 // The max capacity should not change because we have not called
4894 // `run_pending_tasks` yet.
4895 assert_eq!(cache.entry_count(), 0);
4896
4897 cache.run_pending_tasks();
4898 assert_eq!(cache.entry_count(), MAX_CAPACITY);
4899
4900 // Insert more items to the cache.
4901 for i in MAX_CAPACITY..(MAX_CAPACITY * 2) {
4902 let v = format!("v{i}");
4903 cache.insert(i, v)
4904 }
4905 // The max capacity should not change because we have not called
4906 // `run_pending_tasks` yet.
4907 assert_eq!(cache.entry_count(), MAX_CAPACITY);
4908 // Both old and new keys should exist.
4909 assert!(cache.contains_key(&0)); // old
4910 assert!(cache.contains_key(&(MAX_CAPACITY - 1))); // old
4911 assert!(cache.contains_key(&(MAX_CAPACITY * 2 - 1))); // new
4912
4913 // Process the remaining write op logs (there should be MAX_CAPACITY logs),
4914 // and evict the LRU entries.
4915 cache.run_pending_tasks();
4916 assert_eq!(cache.entry_count(), MAX_CAPACITY);
4917
4918 // Now all the old keys should be gone.
4919 assert!(!cache.contains_key(&0));
4920 assert!(!cache.contains_key(&(MAX_CAPACITY - 1)));
4921 // And the new keys should exist.
4922 assert!(cache.contains_key(&(MAX_CAPACITY * 2 - 1)));
4923 }
4924
4925 #[test]
4926 fn slow_eviction_listener() {
4927 const MAX_CAPACITY: u64 = 20;
4928
4929 const EVICTION_TIMEOUT: Duration = Duration::from_millis(30);
4930 const LISTENER_DELAY: Duration = Duration::from_millis(11);
4931 const MAX_LOG_SYNC_REPEATS: u32 = 1;
4932 const EVICTION_BATCH_SIZE: u32 = 1;
4933
4934 let hk_conf = HousekeeperConfig::new(
4935 Some(EVICTION_TIMEOUT),
4936 Some(MAX_LOG_SYNC_REPEATS),
4937 Some(EVICTION_BATCH_SIZE),
4938 );
4939
4940 let (clock, mock) = Clock::mock();
4941 let listener_call_count = Arc::new(AtomicU8::new(0));
4942 let lcc = Arc::clone(&listener_call_count);
4943
4944 // A slow eviction listener that spend `LISTENER_DELAY` to process a removal
4945 // notification.
4946 let listener = move |_k, _v, _cause| {
4947 mock.increment(LISTENER_DELAY);
4948 lcc.fetch_add(1, Ordering::AcqRel);
4949 };
4950
4951 // Create a cache with the LRU policy.
4952 let mut cache = Cache::builder()
4953 .max_capacity(MAX_CAPACITY)
4954 .eviction_policy(EvictionPolicy::lru())
4955 .eviction_listener(listener)
4956 .housekeeper_config(hk_conf)
4957 .clock(clock)
4958 .build();
4959 cache.reconfigure_for_testing();
4960
4961 // Make the cache exterior immutable.
4962 let cache = cache;
4963
4964 // Fill the cache.
4965 for i in 0..MAX_CAPACITY {
4966 let v = format!("v{i}");
4967 cache.insert(i, v)
4968 }
4969 // The max capacity should not change because we have not called
4970 // `run_pending_tasks` yet.
4971 assert_eq!(cache.entry_count(), 0);
4972
4973 cache.run_pending_tasks();
4974 assert_eq!(listener_call_count.load(Ordering::Acquire), 0);
4975 assert_eq!(cache.entry_count(), MAX_CAPACITY);
4976
4977 // Insert more items to the cache.
4978 for i in MAX_CAPACITY..(MAX_CAPACITY * 2) {
4979 let v = format!("v{i}");
4980 cache.insert(i, v);
4981 }
4982 assert_eq!(cache.entry_count(), MAX_CAPACITY);
4983
4984 cache.run_pending_tasks();
4985 // Because of the slow listener, cache should get an over capacity.
4986 let mut expected_call_count = 3;
4987 assert_eq!(
4988 listener_call_count.load(Ordering::Acquire) as u64,
4989 expected_call_count
4990 );
4991 assert_eq!(cache.entry_count(), MAX_CAPACITY * 2 - expected_call_count);
4992
4993 loop {
4994 cache.run_pending_tasks();
4995
4996 expected_call_count += 3;
4997 if expected_call_count > MAX_CAPACITY {
4998 expected_call_count = MAX_CAPACITY;
4999 }
5000
5001 let actual_count = listener_call_count.load(Ordering::Acquire) as u64;
5002 assert_eq!(actual_count, expected_call_count);
5003 let expected_entry_count = MAX_CAPACITY * 2 - expected_call_count;
5004 assert_eq!(cache.entry_count(), expected_entry_count);
5005
5006 if expected_call_count >= MAX_CAPACITY {
5007 break;
5008 }
5009 }
5010
5011 assert_eq!(cache.entry_count(), MAX_CAPACITY);
5012 }
5013
5014 // NOTE: To enable the panic logging, run the following command:
5015 //
5016 // RUST_LOG=moka=info cargo test --features 'logging' -- \
5017 // sync::cache::tests::recover_from_panicking_eviction_listener --exact --nocapture
5018 //
5019 #[test]
5020 fn recover_from_panicking_eviction_listener() {
5021 #[cfg(feature = "logging")]
5022 let _ = env_logger::builder().is_test(true).try_init();
5023
5024 // The following `Vec`s will hold actual and expected notifications.
5025 let actual = Arc::new(Mutex::new(Vec::new()));
5026 let mut expected = Vec::new();
5027
5028 // Create an eviction listener that panics when it see
5029 // a value "panic now!".
5030 let a1 = Arc::clone(&actual);
5031 let listener = move |k, v, cause| {
5032 if v == "panic now!" {
5033 panic!("Panic now!");
5034 }
5035 a1.lock().push((k, v, cause))
5036 };
5037
5038 // Create a cache with the eviction listener.
5039 let mut cache = Cache::builder()
5040 .name("My Sync Cache")
5041 .eviction_listener(listener)
5042 .build();
5043 cache.reconfigure_for_testing();
5044
5045 // Make the cache exterior immutable.
5046 let cache = cache;
5047
5048 // Insert an okay value.
5049 cache.insert("alice", "a0");
5050 cache.run_pending_tasks();
5051
5052 // Insert a value that will cause the eviction listener to panic.
5053 cache.insert("alice", "panic now!");
5054 expected.push((Arc::new("alice"), "a0", RemovalCause::Replaced));
5055 cache.run_pending_tasks();
5056
5057 // Insert an okay value. This will replace the previous
5058 // value "panic now!" so the eviction listener will panic.
5059 cache.insert("alice", "a2");
5060 cache.run_pending_tasks();
5061 // No more removal notification should be sent.
5062
5063 // Invalidate the okay value.
5064 cache.invalidate(&"alice");
5065 cache.run_pending_tasks();
5066
5067 verify_notification_vec(&cache, actual, &expected);
5068 }
5069
5070 // This test ensures that the `contains_key`, `get` and `invalidate` can use
5071 // borrowed form `&[u8]` for key with type `Vec<u8>`.
5072 // https://github.com/moka-rs/moka/issues/166
5073 #[test]
5074 fn borrowed_forms_of_key() {
5075 let cache: Cache<Vec<u8>, ()> = Cache::new(1);
5076
5077 let key = vec![1_u8];
5078 cache.insert(key.clone(), ());
5079
5080 // key as &Vec<u8>
5081 let key_v: &Vec<u8> = &key;
5082 assert!(cache.contains_key(key_v));
5083 assert_eq!(cache.get(key_v), Some(()));
5084 cache.invalidate(key_v);
5085
5086 cache.insert(key, ());
5087
5088 // key as &[u8]
5089 let key_s: &[u8] = &[1_u8];
5090 assert!(cache.contains_key(key_s));
5091 assert_eq!(cache.get(key_s), Some(()));
5092 cache.invalidate(key_s);
5093 }
5094
5095 // Ignored by default. This test becomes unstable when run in parallel with
5096 // other tests.
5097 #[test]
5098 #[ignore]
5099 fn drop_value_immediately_after_eviction() {
5100 use crate::common::test_utils::{Counters, Value};
5101
5102 const MAX_CAPACITY: u32 = 500;
5103 const KEYS: u32 = ((MAX_CAPACITY as f64) * 1.2) as u32;
5104
5105 let counters = Arc::new(Counters::default());
5106 let counters1 = Arc::clone(&counters);
5107
5108 let listener = move |_k, _v, cause| match cause {
5109 RemovalCause::Size => counters1.incl_evicted(),
5110 RemovalCause::Explicit => counters1.incl_invalidated(),
5111 _ => (),
5112 };
5113
5114 let mut cache = Cache::builder()
5115 .max_capacity(MAX_CAPACITY as u64)
5116 .eviction_listener(listener)
5117 .build();
5118 cache.reconfigure_for_testing();
5119
5120 // Make the cache exterior immutable.
5121 let cache = cache;
5122
5123 for key in 0..KEYS {
5124 let value = Arc::new(Value::new(vec![0u8; 1024], &counters));
5125 cache.insert(key, value);
5126 counters.incl_inserted();
5127 cache.run_pending_tasks();
5128 }
5129
5130 let eviction_count = KEYS - MAX_CAPACITY;
5131
5132 cache.run_pending_tasks();
5133 assert_eq!(counters.inserted(), KEYS, "inserted");
5134 assert_eq!(counters.value_created(), KEYS, "value_created");
5135 assert_eq!(counters.evicted(), eviction_count, "evicted");
5136 assert_eq!(counters.invalidated(), 0, "invalidated");
5137 assert_eq!(counters.value_dropped(), eviction_count, "value_dropped");
5138
5139 for key in 0..KEYS {
5140 cache.invalidate(&key);
5141 cache.run_pending_tasks();
5142 }
5143
5144 cache.run_pending_tasks();
5145 assert_eq!(counters.inserted(), KEYS, "inserted");
5146 assert_eq!(counters.value_created(), KEYS, "value_created");
5147 assert_eq!(counters.evicted(), eviction_count, "evicted");
5148 assert_eq!(counters.invalidated(), MAX_CAPACITY, "invalidated");
5149 assert_eq!(counters.value_dropped(), KEYS, "value_dropped");
5150
5151 std::mem::drop(cache);
5152 assert_eq!(counters.value_dropped(), KEYS, "value_dropped");
5153 }
5154
5155 // For testing the issue reported by: https://github.com/moka-rs/moka/issues/383
5156 //
5157 // Ignored by default. This test becomes unstable when run in parallel with
5158 // other tests.
5159 #[test]
5160 #[ignore]
5161 fn ensure_gc_runs_when_dropping_cache() {
5162 let cache = Cache::builder().build();
5163 let val = Arc::new(0);
5164 {
5165 let val = Arc::clone(&val);
5166 cache.get_with(1, move || val);
5167 }
5168 drop(cache);
5169 assert_eq!(Arc::strong_count(&val), 1);
5170 }
5171
5172 #[test]
5173 fn test_debug_format() {
5174 let cache = Cache::new(10);
5175 cache.insert('a', "alice");
5176 cache.insert('b', "bob");
5177 cache.insert('c', "cindy");
5178
5179 let debug_str = format!("{cache:?}");
5180 assert!(debug_str.starts_with('{'));
5181 assert!(debug_str.contains(r#"'a': "alice""#));
5182 assert!(debug_str.contains(r#"'b': "bob""#));
5183 assert!(debug_str.contains(r#"'c': "cindy""#));
5184 assert!(debug_str.ends_with('}'));
5185 }
5186
5187 type NotificationTuple<K, V> = (Arc<K>, V, RemovalCause);
5188
5189 fn verify_notification_vec<K, V, S>(
5190 cache: &Cache<K, V, S>,
5191 actual: Arc<Mutex<Vec<NotificationTuple<K, V>>>>,
5192 expected: &[NotificationTuple<K, V>],
5193 ) where
5194 K: std::hash::Hash + Eq + std::fmt::Debug + Send + Sync + 'static,
5195 V: Eq + std::fmt::Debug + Clone + Send + Sync + 'static,
5196 S: std::hash::BuildHasher + Clone + Send + Sync + 'static,
5197 {
5198 // Retries will be needed when testing in a QEMU VM.
5199 const MAX_RETRIES: usize = 5;
5200 let mut retries = 0;
5201 loop {
5202 // Ensure all scheduled notifications have been processed.
5203 cache.run_pending_tasks();
5204 std::thread::sleep(Duration::from_millis(500));
5205
5206 let actual = &*actual.lock();
5207 if actual.len() != expected.len() {
5208 if retries <= MAX_RETRIES {
5209 retries += 1;
5210 continue;
5211 } else {
5212 assert_eq!(actual.len(), expected.len(), "Retries exhausted");
5213 }
5214 }
5215
5216 for (i, (actual, expected)) in actual.iter().zip(expected).enumerate() {
5217 assert_eq!(actual, expected, "expected[{i}]");
5218 }
5219
5220 break;
5221 }
5222 }
5223}