The implementation provides a working concurrent hash map using lock striping to minimize contention. Writer threads insert new entries while reader threads access existing ones, and the final assertion confirms the expected size after all operations complete.</think>
# Concurrent Hash Map with Lock Striping
Here's a production-quality implementation of a segmented concurrent hash map similar to Java's ConcurrentHashMap:
```rust
use std::collections::HashMap;
use std::sync::{Arc, RwLock};
use std::hash::{Hash, Hasher};
use std::collections::hash_map::DefaultHasher;
/// A thread-safe hash map using lock striping with 16 segments.
/// Each segment has its own read-write lock, allowing concurrent access
/// to different segments without contention.
pub struct ConcurrentHashMap<K, V> {
segments: Vec<Arc<RwLock<HashMap<K, V>>>>,
num_segments: usize,
}
impl<K: Hash + Eq + Clone, V: Clone> ConcurrentHashMap<K, V> {
/// Creates a new concurrent hash map with 16 segments
pub fn new() -> Self {
Self::with_capacity(16)
}
/// Creates a new concurrent hash map with the specified number of segments
pub fn with_capacity(num_segments: usize) -> Self {
assert!(num_segments > 0, "Number of segments must be > 0");
let mut segments = Vec::with_capacity(num_segments);
for _ in 0..num_segments {
segments.push(Arc::new(RwLock::new(HashMap::new())));
}
ConcurrentHashMap {
segments,
num_segments,
}
}
/// Determines which segment a key belongs to
#[inline]
fn segment_index(&self, key: &K) -> usize {
let mut hasher = DefaultHasher::new();
key.hash(&mut hasher);
(hasher.finish() as usize) % self.num_segments
}
/// Inserts or updates a key-value pair
///
/// # Returns
/// The previous value if the key existed, or None if this is a new key
pub fn insert(&self, key: K, value: V) -> Option<V> {
let idx = self.segment_index(&key);
let mut segment = self.segments[idx].write().unwrap();
segment.insert(key, value)
}
/// Gets a value by key
///
/// # Returns
/// A clone of the value if found, or None otherwise
pub fn get(&self, key: &K) -> Option<V> {
let idx = self.segment_index(key);
let segment = self.segments[idx].read().unwrap();
segment.get(key).cloned()
}
/// Gets a reference to a value by key
///
/// # Note
/// This acquires a read lock and holds it while the callback executes.
/// The callback should be fast to avoid blocking other readers.
pub fn get_ref<F, R>(&self, key: &K, f: F) -> Option<R>
where
F: FnOnce(&V) -> R,
{
let idx = self.segment_index(key);
let segment = self.segments[idx].read().unwrap();
segment.get(key).map(f)
}
/// Removes a key-value pair
///
/// # Returns
/// The removed value if found, or None otherwise
pub fn remove(&self, key: &K) -> Option<V> {
let idx = self.segment_index(key);
let mut segment = self.segments[idx].write().unwrap();
segment.remove(key)
}
/// Checks if a key exists in the map
pub fn contains_key(&self, key: &K) -> bool {
let idx = self.segment_index(key);
let segment = self.segments[idx].read().unwrap();
segment.contains_key(key)
}
/// Updates or inserts a value, returning the final value
pub fn put_if_absent(&self, key: K, value: V) -> V {
let idx = self.segment_index(&key);
let mut segment = self.segments[idx].write().unwrap();
segment.entry(key).or_insert(value).clone()
}
/// Applies a function to update the value for a key
pub fn compute<F>(&self, key: K, mut f: F) -> Option<V>
where
F: FnMut(Option<V>) -> Option<V>,
{
let idx = self.segment_index(&key);
let mut segment = self.segments[idx].write().unwrap();
let old_value = segment.remove(&key);
match f(old_value) {
Some(new_value) => {
segment.insert(key, new_value.clone());
Some(new_value)
}
None => None,
}
}
/// Returns the total number of entries across all segments
pub fn len(&self) -> usize {
self.segments
.iter()
.map(|segment| {
let seg = segment.read().unwrap();
seg.len()
})
.sum()
}
/// Returns true if the map is empty
pub fn is_empty(&self) -> bool {
self.segments
.iter()
.all(|segment| {
let seg = segment.read().unwrap();
seg.is_empty()
})
}
/// Clears all entries from all segments
pub fn clear(&self) {
for segment in &self.segments {
let mut seg = segment.write().unwrap();
seg.clear();
}
}
/// Returns the size of each segment (for diagnostics)
pub fn segment_sizes(&self) -> Vec<usize> {
self.segments
.iter()
.map(|segment| {
let seg = segment.read().unwrap();
seg.len()
})
.collect()
}
/// Collects all entries into a Vec (acquires all locks)
pub fn iter_snapshot(&self) -> Vec<(K, V)> {
let mut result = Vec::new();
for segment in &self.segments {
let seg = segment.read().unwrap();
for (k, v) in seg.iter() {
result.push((k.clone(), v.clone()));
}
}
result
}
/// Applies a function to each entry (acquires read locks)
pub fn for_each<F>(&self, mut f: F)
where
F: FnMut(K, V),
{
for segment in &self.segments {
let seg = segment.read().unwrap();
for (k, v) in seg.iter() {
f(k.clone(), v.clone());
}
}
}
/// Returns the number of segments
pub fn num_segments(&self) -> usize {
self.num_segments
}
}
impl<K: Hash + Eq + Clone, V: Clone> Default for ConcurrentHashMap<K, V> {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use std::thread;
use std::time::Duration;
#[test]
fn test_basic_operations() {
let map = ConcurrentHashMap::new();
// Insert
assert_eq!(map.insert("key1", "value1"), None);
assert_eq!(map.get(&"key1"), Some("value1"));
// Update
assert_eq!(map.insert("key1", "value2"), Some("value1"));
assert_eq!(map.get(&"key1"), Some("value2"));
// Remove
assert_eq!(map.remove(&"key1"), Some("value2"));
assert_eq!(map.get(&"key1"), None);
}
#[test]
fn test_contains_key() {
let map = ConcurrentHashMap::new();
assert!(!map.contains_key(&42));
map.insert(42, "value");
assert!(map.contains_key(&42));
}
#[test]
fn test_put_if_absent() {
let map = ConcurrentHashMap::new();
let result1 = map.put_if_absent("key", "value1");
assert_eq!(result1, "value1");
let result2 = map.put_if_absent("key", "value2");
assert_eq!(result2, "value1"); // Original value unchanged
}
#[test]
fn test_compute() {
let map = ConcurrentHashMap::new();
// Insert via compute
let result = map.compute("key", |_| Some(10));
assert_eq!(result, Some(10));
// Update via compute
let result = map.compute("key", |val| {
val.map(|v| v + 5)
});
assert_eq!(result, Some(15));
// Remove via compute
let result = map.compute("key", |_| None);
assert_eq!(result, None);
assert_eq!(map.get(&"key"), None);
}
#[test]
fn test_concurrent_writes_different_segments() {
let map = Arc::new(ConcurrentHashMap::new());
let mut handles = vec![];
// 10 threads each writing 100 entries to different keys
for thread_id in 0..10 {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for i in 0..100 {
let key = format!("thread_{}_key_{}", thread_id, i);
let value = thread_id * 100 + i;
map.insert(key, value);
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
assert_eq!(map.len(), 1000);
}
#[test]
fn test_concurrent_reads_and_writes() {
let map = Arc::new(ConcurrentHashMap::new());
// Pre-populate
for i in 0..100 {
map.insert(i, i * 2);
}
let mut handles = vec![];
// Writer threads
for writer_id in 0..5 {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for i in 0..50 {
let key = 100 + writer_id * 50 + i;
map.insert(key, key * 2);
thread::yield_now();
}
});
handles.push(handle);
}
// Reader threads
for _ in 0..5 {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for i in 0..100 {
let _ = map.get(&i);
thread::yield_now();
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
assert_eq!(map.len(), 350);
}
#[test]
fn test_concurrent_same_segment_writes() {
let map = Arc::new(ConcurrentHashMap::with_capacity(4));
let mut handles = vec![];
// Multiple threads writing to keys that hash to the same segment
for thread_id in 0..5 {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for i in 0..20 {
let key = format!("{}_key_{}", thread_id, i);
map.insert(key, thread_id * 100 + i);
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
assert_eq!(map.len(), 100);
}
#[test]
fn test_no_deadlock_on_clear() {
let map = Arc::new(ConcurrentHashMap::new());
for i in 0..50 {
map.insert(i, i * 2);
}
let mut handles = vec![];
// Multiple readers and a clearer
for _ in 0..5 {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for i in 0..100 {
let _ = map.get(&(i % 50));
}
});
handles.push(handle);
}
let map_clear = Arc::clone(&map);
thread::sleep(Duration::from_millis(10));
map_clear.clear();
for handle in handles {
handle.join().unwrap();
}
assert_eq!(map.len(), 0);
}
#[test]
fn test_segment_load_distribution() {
let map = ConcurrentHashMap::new();
// Insert 160 items across 16 segments
for i in 0..160 {
map.insert(i, i * 2);
}
let sizes = map.segment_sizes();
println!("Segment sizes: {:?}", sizes);
println!("Sum: {}", sizes.iter().sum::<usize>());
// Verify all items are present
assert_eq!(map.len(), 160);
assert!(sizes.iter().all(|&size| size > 0)); // All segments have items
}
#[test]
fn test_snapshot_iteration() {
let map = ConcurrentHashMap::new();
for i in 0..10 {
map.insert(i, i * 2);
}
let snapshot = map.iter_snapshot();
assert_eq!(snapshot.len(), 10);
for (k, v) in snapshot {
assert_eq!(map.get(&k), Some(v));
}
}
#[test]
fn test_for_each() {
let map = ConcurrentHashMap::new();
for i in 0..10 {
map.insert(i, i * 2);
}
let mut count = 0;
map.for_each(|_k, _v| {
count += 1;
});
assert_eq!(count, 10);
}
#[test]
fn test_get_ref() {
let map = ConcurrentHashMap::new();
map.insert("key", vec![1, 2, 3]);
let result = map.get_ref(&"key", |v| v.len());
assert_eq!(result, Some(3));
}
#[test]
fn test_stress_test() {
let map = Arc::new(ConcurrentHashMap::new());
let mut handles = vec![];
const NUM_THREADS: usize = 20;
const OPERATIONS_PER_THREAD: usize = 1000;
for thread_id in 0..NUM_THREADS {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for op in 0..OPERATIONS_PER_THREAD {
let key_base = op % 100;
match op % 3 {
0 => {
map.insert(key_base, op);
}
1 => {
let _ = map.get(&key_base);
}
_ => {
let _ = map.remove(&key_base);
}
}
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
// Just verify it completes without panicking
assert!(map.len() <= 100);
}
}
#[cfg(test)]
mod benchmarks {
use super::*;
use std::sync::Arc;
use std::thread;
use std::time::Instant;
#[test]
#[ignore] // Run with: cargo test --release -- --ignored --nocapture
fn bench_concurrent_writes() {
let map = Arc::new(ConcurrentHashMap::new());
let start = Instant::now();
let mut handles = vec![];
for thread_id in 0..16 {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for i in 0..10000 {
let key = format!("thread_{}_key_{}", thread_id, i);
map.insert(key, i);
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
let elapsed = start.elapsed();
let total_ops = 16 * 10000;
println!("Concurrent writes: {:.2}M ops/sec",
total_ops as f64 / elapsed.as_secs_f64() / 1_000_000.0);
}
#[test]
#[ignore]
fn bench_concurrent_reads_writes() {
let map = Arc::new(ConcurrentHashMap::new());
// Pre-populate
for i in 0..1000 {
map.insert(i, i * 2);
}
let start = Instant::now();
let mut handles = vec![];
for _ in 0..8 {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for i in 0..50000 {
let _ = map.get(&(i % 1000));
}
});
handles.push(handle);
}
for _ in 0..8 {
let map = Arc::clone(&map);
let handle = thread::spawn(move || {
for i in 0..10000 {
map.insert(1000 + i, i);
}
});
handles.push(handle);
}
for handle in handles {
handle.join().unwrap();
}
let elapsed = start.elapsed();
let total_ops = 8 * 50000 + 8 * 10000;
println!("Mixed reads/writes: {:.2}M ops/sec",
total_ops as f64 / elapsed.as_secs_f64() / 1_000_000.0);
}
}