Arc Swap Config Reload Hot
Reload configuration atomically with arc_swap for lock-free hot config updates.
Code
use arc_swap::ArcSwap;
use std::sync::Arc;
use std::time::Duration;
use tokio::time::sleep;
struct Config { port: u16, debug: bool }
static CONFIG: ArcSwap<Config> = ArcSwap::from_pointee(Config { port: 8080, debug: false });
fn get_config() -> Arc<Config> { CONFIG.load_full() }
fn reload(config: Config) { CONFIG.store(Arc::new(config)); }
#[tokio::main]
async fn main() {
println!("port: {}", get_config().port);
reload(Config { port: 9090, debug: true });
sleep(Duration::from_millis(10)).await;
println!("port: {}", get_config().port);
}What the code does
Count the functions get_config, reload and main as the entire surface area of Arc Swap Config Reload Hot.
Points of care
- Dependency check:
arc_swap::ArcSwapandtokio::time::sleep— not built-in, must be present in the project.
Using it
The primary signature is fn get_config() -> Arc<Config>
The demo output is labeled (port:), so every printed line maps back to its originating operation.
main is the driver: it invokes get_config and reload before returning.
Key statements
fn reload(config: Config) { CONFIG.store(Arc::new(config)); }
fn get_config() -> Arc<Config> { CONFIG.load_full() }
async fn main() {
println!("port: {}", get_config().port);
reload(Config { port: 9090, debug: true });
sleep(Duration::from_millis(10)).await;
println!("port: {}", get_config().port);
}
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
- Which packages must be installed first?
- Yes. The imports resolve to `arc_swap::ArcSwap` and `tokio::time::sleep`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.