once_cell / LazyLock & dashmap
LazyLock (stdlib since Rust 1.80) initializes globals on first access. dashmap is a concurrent HashMap for caches and registries without a global mutex.
Search across all documentation pages
LazyLock (stdlib since Rust 1.80) initializes globals on first access. dashmap is a concurrent HashMap for caches and registries without a global mutex.
use std::sync::LazyLock;
static CONFIG: LazyLock<String> = LazyLock::new(|| {
std::env::var("APP_NAME").unwrap_or_else(|_| "app".into())
});dashmap = "6"use dashmap::DashMap;
use std::sync::Arc;
fn main() {
let cache: Arc<DashMap<String, u64>> = Arc::new(DashMap::new());
cache.insert("user:1".into(), 42);
assert_eq!(*cache.get("user:1").unwrap(), 42);
}When to reach for this:
use std::sync::LazyLock;
use dashmap::DashMap;
static METRICS: LazyLock<DashMap<&'static str, u64>> =
LazyLock::new(DashMap::new);
fn inc(name: &'static str) {
*METRICS.entry(name).or_insert(0) += 1;
}
fn main() {
inc("requests");
inc("requests");
assert_eq!(*METRICS.get("requests").unwrap(), 2);
}What this demonstrates:
LazyLock replaces once_cell::sync::Lazy for new codeDashMap allows concurrent insert/getArc<DashMap> in Axum state for testability| Tool | Status |
|---|---|
std::sync::LazyLock | Preferred on Rust 1.80+ |
once_cell | Still used in older MSRV crates |
tokio::sync::OnceCell | Async initialization |
DashMap shards locks internally; better for many readers/writers on independent keys. Single-key hot spots still contend.
LazyLock, Mutex, or DashMap.moka crate.Result from inner setup or use OnceLock<Result<T>>.| Alternative | Use When | Don't Use When |
|---|---|---|
RwLock<HashMap> | Low contention | Many concurrent keys |
moka / cached | TTL caches | Simple counters |
tokio::sync::Mutex<HashMap> | Async-only single lock | High read concurrency |
Rarely for LazyLock. once_cell remains for ecosystem crates not yet migrated.
Sync API is fine for short critical sections; avoid long awaits while holding shard locks.
Prefer injecting Arc<DashMap> via app state instead of statics in tests.
Rust 1.97 includes LazyLock. Document MSRV if supporting older compilers with once_cell.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 19, 2026