Expand description
Sharded lock implementation for improved concurrent performance Copyright © 2025-2026 Wenze Wei. All Rights Reserved.
This file is part of Ri. The Ri project belongs to the Dunimd Team.
Licensed under the Apache License, Version 2.0 (the “License”); You may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
§Sharded Lock Implementation
This module provides a sharded lock data structure (RiShardedLock) that
improves concurrent performance by reducing lock contention. Instead of using
a single global lock, the data is partitioned into multiple shards, each with
its own lock.
§Key Benefits
- Reduced Lock Contention: Multiple threads can access different shards simultaneously
- Better Scalability: Performance improves with more shards for high-concurrency scenarios
- Uniform Distribution: Uses hash-based sharding for even key distribution
- Thread Safety: All operations are thread-safe using async RwLock
§Design Principles
- Sharding Strategy: Keys are distributed using
hash(key) % shard_count - Lock Granularity: Each shard has its own RwLock for fine-grained locking
- Default Shard Count: 16 shards by default, configurable based on workload
- Zero-Cost Abstraction: Sharding adds minimal overhead to operations
§Usage Example
use ri::core::concurrent::RiShardedLock;
use std::collections::HashMap;
let sharded_map = RiShardedLock::<String, String>::new(16);
// Insert a value
sharded_map.insert("key1".to_string(), "value1".to_string()).await;
// Get a value
let value = sharded_map.get("key1").await;
// Remove a value
sharded_map.remove("key1").await;