Using Box::leak for a shared state

⚓ Rust    📅 2025-10-13    👤 surdeus    👁️ 7      

surdeus

Warning

This post was published 50 days ago. The information described in this article may have changed.

I'm building an HTTP server using Hyper, and I'm wondering if there are any concerns about using Box::leak for a shared state.

In Hyper's examples, an Arc is used to pass a shared state to the service_fn (see here).

However, since I can guarantee that the shared state will last for the entire application, I think passing around a static reference to the state would be possible (and more efficient).

I don't want to use a static variable because I want to be able to create multiple independent states for testing purposes.

This would be my adapted hyper example:

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr: SocketAddr = ([127, 0, 0, 1], 4000).into();

    // Using Box::leak instead of Arc.
    let counter: &'static AtomicUsize = Box::leak(Box::new(AtomicUsize::new(0)));
    // let counter = Arc::new(AtomicUsize::new(0));

    let listener = TcpListener::bind(addr).await?;
    println!("Listening on http://{}", addr);
    loop {
        let (stream, _) = listener.accept().await?;
        let io = TokioIo::new(stream);

        let service = service_fn(move |_req| {
            let count = counter.fetch_add(1, Ordering::AcqRel);
            async move {
                Ok::<_, Error>(Response::new(Full::new(Bytes::from(format!(
                    "Request #{}",
                    count
                )))))
            }
        });

        if let Err(err) = http1::Builder::new().serve_connection(io, service).await {
            println!("Error serving connection: {:?}", err);
        }
    }
}

1 post - 1 participant

Read full topic

🏷️ Rust_feed