use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::BlockCache;
pub struct ShardedCache<K, V> {
shards: Vec<Mutex<BlockCache<K, V>>>,
contention: AtomicU64,
}
impl<K, V> ShardedCache<K, V>
where
K: Hash + Eq + Clone,
V: Clone,
{
pub fn with_capacity(total_capacity: usize, num_shards: usize) -> Self {
let shards_n = num_shards.max(1).next_power_of_two();
let per_shard = total_capacity.div_ceil(shards_n).max(1);
let mut shards = Vec::with_capacity(shards_n);
for _ in 0..shards_n {
shards.push(Mutex::new(BlockCache::with_capacity(per_shard)));
}
Self {
shards,
contention: AtomicU64::new(0),
}
}
pub fn num_shards(&self) -> usize {
self.shards.len()
}
pub fn contention_events(&self) -> u64 {
self.contention.load(Ordering::Relaxed)
}
pub fn len(&self) -> usize {
self.shards.iter().map(|m| m.lock().unwrap().len()).sum()
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
fn shard_index(&self, key: &K) -> usize {
let mut h = DefaultHasher::new();
key.hash(&mut h);
(h.finish() as usize) & (self.shards.len() - 1)
}
pub fn get(&self, key: &K) -> Option<V> {
let idx = self.shard_index(key);
let guard = self.lock_with_contention(idx);
let mut g = guard;
g.get(key).cloned()
}
pub fn put(&self, key: K, value: V) -> Option<(K, V)> {
let idx = self.shard_index(&key);
let mut g = self.lock_with_contention(idx);
g.put(key, value)
}
pub fn remove(&self, key: &K) -> Option<V> {
let idx = self.shard_index(key);
let mut g = self.lock_with_contention(idx);
g.remove(key)
}
pub fn clear(&self) {
for shard in &self.shards {
shard.lock().unwrap().clear();
}
}
fn lock_with_contention(&self, idx: usize) -> std::sync::MutexGuard<'_, BlockCache<K, V>> {
match self.shards[idx].try_lock() {
Ok(g) => g,
Err(_) => {
self.contention.fetch_add(1, Ordering::Relaxed);
self.shards[idx].lock().unwrap()
}
}
}
}
#[cfg(test)]
#[path = "concurrent_shards_tests.rs"]
mod tests;