Arc Swap Config Reload
Reload configuration atomically by swapping an Arc while readers keep lock-free snapshots, with no downtime or partial state.
Code
use arc_swap::ArcSwap;
use std::sync::Arc;
#[derive(Debug, Clone, PartialEq)]
struct Config {
max_connections: usize,
feature_flag: bool,
}
struct ConfigStore {
current: ArcSwap<Config>,
}
impl ConfigStore {
fn new(initial: Config) -> Self {
Self {
current: ArcSwap::from_pointee(initial),
}
}
fn load(&self) -> Arc<Config> {
self.current.load_full()
}
fn reload(&self, next: Config) -> Arc<Config> {
self.current.swap(Arc::new(next))
}
}
fn main() {
let store = ConfigStore::new(Config {
max_connections: 8,
feature_flag: false,
});
let snapshot = store.load();
let previous = store.reload(Config {
max_connections: 16,
feature_flag: true,
});
println!("previous: {:?}", previous);
println!("snapshot: {:?}", snapshot);
println!("current: {:?}", store.load());
assert_eq!(store.load().max_connections, 16);
}How it works
Count the functions new, load, reload and main as the entire surface area of Arc Swap Config Reload.
What to watch for
- Plan for an install step:
arc_swap::ArcSwapis a real dependency, resolved by the package manager.
Using it
Signature: fn new(initial: Config) -> Self
The demo output is labeled (previous:, snapshot:, current:), so every printed line maps back to its originating operation.
The sequence new, load and reload lives in main; running the file triggers it.
Key statements
fn reload(&self, next: Config) -> Arc<Config> {
self.current.swap(Arc::new(next))
}
fn new(initial: Config) -> Self {
Self {
current: ArcSwap::from_pointee(initial),
}
}
fn load(&self) -> Arc<Config> {
self.current.load_full()
}
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does this need from the package registry?
- These are real dependencies: `arc_swap::ArcSwap`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.