Scalable Concurrent Containers
A collection of high performance containers and utilities for concurrent and asynchronous programming.
Features
- Asynchronous counterparts to blocking and synchronous methods.
- Formally verified EBR implementation.
- Near-linear scalability.
- No spin-locks and no busy loops.
- Zero dependencies on other crates.
- Serde support:
features = ["serde"]
.
Concurrent and Asynchronous Containers
- HashMap is a concurrent and asynchronous hash map.
- HashSet is a concurrent and asynchronous hash set.
- HashIndex is a read-optimized concurrent and asynchronous hash map.
- HashCache is a sampling-based LRU cache backed by HashMap.
- TreeIndex is a read-optimized concurrent and asynchronous B-plus tree.
Utilities for Concurrent Programming
- EBR implements lock-free epoch-based reclamation.
- LinkedList is a type trait implementing a lock-free concurrent singly linked list.
- Queue is a concurrent lock-free first-in-first-out container.
- Stack is a concurrent lock-free last-in-first-out container.
- Bag is a concurrent lock-free unordered opaque container.
HashMap
HashMap is a concurrent hash map that is targeted at highly concurrent write-heavy workloads. HashMap is basically an array of entry buckets where each bucket is protected by a special read-write lock providing both blocking and asynchronous methods. The bucket array is fully managed by EBR enabling lock-free access to it and non-blocking array resizing.
Locking behavior
Entry access: fine-grained locking
Read/write access to an entry is serialized by the read-write lock in the bucket containing the entry. There are no container-level locks, therefore, the larger the container gets, the lower the chance of the bucket-level lock being contended.
Resize: lock-free
Resizing of the container is totally non-blocking and lock-free; resizing does not block any other read/write access to the container or resizing attempts. Resizing is analogous to pushing a new bucket array into a lock-free stack. Each individual entry in the old bucket array will be incrementally relocated to the new bucket array on future access to the container, and the old bucket array gets dropped eventually when it becomes empty.
Examples
An entry can be inserted if the key is unique. The inserted entry can be updated, read, and removed synchronously or asynchronously.
use HashMap;
let hashmap: = default;
assert!;
assert_eq!;
assert_eq!;
assert_eq!;
hashmap.entry.or_insert;
assert_eq!;
let future_insert = hashmap.insert_async;
let future_remove = hashmap.remove_async;
upsert
will insert a new entry if the key does not exist, otherwise update the value field.
use HashMap;
let hashmap: = default;
hashmap.upsert;
assert_eq!;
hashmap.upsert;
assert_eq!;
let future_upsert = hashmap.upsert_async;
HashMap does not provide an Iterator since it is impossible to confine the lifetime of Iterator::Item to the Iterator. The limitation can be circumvented by relying on interior mutability, e.g., let the returned reference hold a lock, however it will easily lead to a deadlock if not correctly used, and frequent acquisition of locks may impact performance. Therefore, Iterator is not implemented, instead, HashMap provides a number of methods to iterate over entries synchronously or asynchronously: any
, any_async
, for_each
, for_each_async
, OccupiedEntry::next
, OccupiedEntry::next_async
, retain
, retain_async
, scan
, and scan_async
.
use HashMap;
let hashmap: = default;
assert!;
assert!;
// `for_each` allows entry modification.
let mut acc = 0;
hashmap.for_each;
assert_eq!;
assert_eq!;
assert_eq!;
// `any` returns `true` as soon as an entry satisfying the predicate is found.
assert!;
assert!;
// `retain` enables entry removal.
assert_eq!;
// `hash_map::OccupiedEntry` also can return the next closest occupied entry.
let first_entry = hashmap.first_occupied_entry;
let second_entry = first_entry.and_then;
assert!;
assert!;
// Asynchronous iteration over entries using `scan_async` and `for_each_async`.
let future_scan = hashmap.scan_async;
let future_for_each = hashmap.for_each_async;
HashSet
HashSet is a special version of HashMap where the value type is ()
.
Examples
Most HashSet methods are identical to that of HashMap except that they do not receive a value argument, and some HashMap methods for value modification are not implemented for HashSet.
use HashSet;
let hashset: = default;
assert!;
assert!;
assert!;
let future_insert = hashset.insert_async;
let future_remove = hashset.remove_async;
HashIndex
HashIndex is a read-optimized version of HashMap. In a HashIndex, not only is the memory of the bucket array managed by EBR, but also that of entry buckets is protected by EBR, enabling lock-free read access to individual entries.
Examples
The read
method is completely lock-free.
use ModifyAction;
use HashIndex;
let hashindex: = default;
assert!;
assert_eq!;
let future_insert = hashindex.insert_async;
let future_remove = hashindex.remove_if_async;
An Iterator is implemented for HashIndex, because any derived references can survive as long as the associated ebr::Barrier
lives.
use Barrier;
use HashIndex;
let hashindex: = default;
assert!;
// Existing values can be replaced with new ones.
assert!;
let barrier = new;
// An `ebr::Barrier` has to be supplied to `iter`.
let mut iter = hashindex.iter;
// The derived reference can live as long as `barrier`.
let entry_ref = iter.next.unwrap;
assert_eq!;
drop;
// The entry can be read after `hashindex` is dropped.
assert_eq!;
HashCache
HashCache is a concurrent sampling-based LRU cache that is based on the HashMap implementation. HashCache does not keep track of the least recently used entry in the entire cache, instead each bucket maintains a doubly linked list of occupied entries which is updated on access to entries in order to keep track of the least recently used entry within the bucket.
Examples
The LRU entry in a bucket is evicted when a new entry is being inserted and the bucket is full.
use HashCache;
let hashcache: = with_capacity;
/// The capacity cannot exceed the maximum capacity.
assert_eq!;
/// If the bucket corresponding to `1` or `2` is full, the LRU entry will be evicted.
assert!;
assert!;
/// `1` becomes the most recently accessed entry in the bucket.
assert!;
/// An entry can be normally removed.
assert_eq!;
TreeIndex
TreeIndex is a B-plus tree variant optimized for read operations. EBR protects the memory used by individual entries, thus enabling lock-free read access to them.
Locking behavior
Read access is always lock-free and non-blocking. Write access to an entry is also lock-free and non-blocking as long as no structural changes are required. However, when nodes are being split or merged by a write operation, other write operations on keys in the affected range are blocked.
Examples
An entry can be inserted if the key is unique, and it can be read, and removed afterwards. Locks are acquired or awaited only when internal nodes are split or merged.
use TreeIndex;
let treeindex: = new;
assert!;
// `read` is lock-free.
assert_eq!;
assert!;
let future_insert = treeindex.insert_async;
let future_remove = treeindex.remove_if_async;
Entries can be scanned without acquiring any locks.
use Barrier;
use TreeIndex;
let treeindex: = new;
assert!;
assert!;
assert!;
let barrier = new;
// `visitor` iterates over entries without acquiring a lock.
let mut visitor = treeindex.iter;
assert_eq!;
assert_eq!;
assert_eq!;
assert!;
A specific range of keys can be scanned.
use Barrier;
use TreeIndex;
let treeindex: = new;
for i in 0..10
let barrier = new;
assert_eq!;
assert_eq!;
assert_eq!;
Bag
Bag is a concurrent lock-free unordered container. Bag is completely opaque, disallowing access to contained instances until they are popped. Bag is especially efficient if the number of contained instances can be maintained under ARRAY_LEN (default: usize::BITS / 2)
Examples
use Bag;
let bag: = default;
bag.push;
assert!;
assert_eq!;
assert!;
Queue
Queue is an EBR backed concurrent lock-free first-in-first-out container.
Examples
use Queue;
let queue: = default;
queue.push;
assert!;
assert!;
assert_eq!;
assert_eq!;
assert!;
Stack
Stack is an EBR backed concurrent lock-free last-in-first-out container.
Examples
use Stack;
let stack: = default;
stack.push;
stack.push;
assert_eq!;
assert_eq!;
assert!;
EBR
The ebr
module implements epoch-based reclamation and various types of auxiliary data structures to make use of it safely. Its epoch-based reclamation algorithm is similar to that implemented in crossbeam_epoch, however users may find it easier to use as the lifetime of an instance is safely managed. For instance, ebr::AtomicArc
and ebr::Arc
hold a strong reference to the underlying instance, and the instance is automatically passed to the garbage collector when the reference count drops to zero.
Examples
The ebr
module can be used without an unsafe
block.
use ;
use Relaxed;
// `atomic_arc` holds a strong reference to `17`.
let atomic_arc: = new;
// `barrier` prevents the garbage collector from dropping reachable instances.
let barrier: Barrier = new;
// `ptr` cannot outlive `barrier`.
let mut ptr: = atomic_arc.load;
assert_eq!;
// `atomic_arc` can be tagged.
atomic_arc.update_tag_if;
// `ptr` is not tagged, so CAS fails.
assert!;
// `ptr` can be tagged.
ptr.set_tag;
// The return value of CAS is a handle to the instance that `atomic_arc` previously owned.
let prev: = atomic_arc.compare_exchange.unwrap.0.unwrap;
assert_eq!;
// `17` will be garbage-collected later.
drop;
// `ebr::AtomicArc` can be converted into `ebr::Arc`.
let arc: = atomic_arc.try_into_arc.unwrap;
assert_eq!;
// `18` will be garbage-collected later.
drop;
// `17` is still valid as `barrier` keeps the garbage collector from dropping it.
assert_eq!;
// Execution of a closure can be deferred until all the current readers are gone.
barrier.defer_execute;
drop;
// If the thread is expected to lie dormant for a while, call `suspend()` to allow other threads
// to reclaim its own retired instances.
suspend;
LinkedList
LinkedList is a type trait that implements lock-free concurrent singly linked list operations, backed by EBR. It additionally provides a method for marking an entry of a linked list to denote a user-defined state.
Examples
use ;
use LinkedList;
use Relaxed;
;
let barrier = new;
let head: L = default;
let tail: = new;
// A new entry is pushed.
assert!;
assert!;
// Users can mark a flag on an entry.
head.mark;
assert!;
// `next_ptr` traverses the linked list.
let next_ptr = head.next_ptr;
assert_eq!;
// Once `tail` is deleted, it becomes invisible.
tail.delete_self;
assert!;
Performance
HashMap and HashIndex
Comparison with DashMap.
- Results on Apple M1 (8 cores).
- Results on Intel Xeon (VM, 40 cores).
- Interpret the results cautiously as benchmarks usually do not represent real world workloads.
EBR
- The average time taken to enter and exit a protected region: 2.1 nanoseconds on Apple M1.