skip to content

In Rust, what happens to a `LazyLock` or an `OnceLock` when its initialiser panics, and what happens when an initialiser reenters the same cell?

level: seniorimportance: nice to knowfreq 20%

answer

  1. one remembers the failure
  2. the other stays empty
  3. poisoning without recovery
  4. reentrancy: panic or deadlock

basics

~20 s

A panicking LazyLock or LazyCell initialiser poisons it, so every later access panics. A panicking OnceLock or OnceCell get_or_init leaves the cell empty, so the next call retries. Reentrant initialisation panics for OnceCell and currently deadlocks for OnceLock.

solid answer

~50 s

The two families treat a panicking initialiser differently. `LazyLock` (and `LazyCell`) owns its closure and can run it only once, so a panic propagates to the caller and **poisons** the lock; every later dereference or `force` panics with "LazyLock instance has previously been poisoned", and unlike a `Mutex` there is no `into_inner` recovery. `OnceLock` (and `OnceCell`) takes the closure per call, so a panic propagates and the cell **stays uninitialised**; std documents `OnceLock` as never poisoned, and the next `get_or_init` runs its closure again. Calling `get_or_init` on the same cell from inside its own closure is documented as an error: `OnceCell` panics with `reentrant init`, while for `OnceLock` the outcome is unspecified and the current implementation deadlocks. A lazy global that touches itself during initialisation, directly or through a chain of other lazy globals, hits the same trap.

code

rust · 17 lines
rust
use std::panic;
use std::sync::{LazyLock, OnceLock};

static SETTINGS: LazyLock<String> = LazyLock::new(|| {
    std::fs::read_to_string("/nonexistent/app.toml").expect("settings file missing")
});
static LIMITS: OnceLock<u32> = OnceLock::new();

fn main() {
    let first = panic::catch_unwind(|| SETTINGS.len());
    let second = panic::catch_unwind(|| SETTINGS.len());
    println!("LazyLock: first err={}, second err={}", first.is_err(), second.is_err());

    let r = panic::catch_unwind(|| *LIMITS.get_or_init(|| panic!("limits not readable")));
    println!("OnceLock after panic: err={}, get={:?}", r.is_err(), LIMITS.get());
    println!("OnceLock retry: {}", LIMITS.get_or_init(|| 64));
}

go deeper

for a junior

Remember that a panic inside a lazy initialiser does not disappear: a LazyLock stays broken, while an OnceLock stays empty and can be filled later.

for a middle

Explain the cause: LazyLock owns an FnOnce closure that is consumed when it runs, while get_or_init brings a new closure on every call.

for a senior

Diagnose the symptoms: repeated "previously been poisoned" panics point at a failed lazy global, and a start-up hang points at a reentrant OnceLock or a cycle between globals.

for a principal

Set the rule that fallible, input-dependent initialisation happens in main, and lazy globals hold only values whose failure is a programming error caught by tests.

## Two designs, two failure modes The once-initialised types in std split into two pairs that behave differently when the initialiser fails by panicking: - **`LazyCell<T, F>` and `LazyLock<T, F>`** (stable since **Rust 1.80**) store the initialising closure `F` inside themselves at construction. The closure is `FnOnce`, so it can be called only once, and it is consumed when it runs. - **`OnceCell<T>` and `OnceLock<T>`** (stable since **Rust 1.70**) store no closure. Each call to `get_or_init` brings its own. That difference decides what a panic leaves behind. ## A panic in a `LazyLock` initialiser: poisoning When the closure in a `LazyLock` panics, the panic propagates to whichever caller triggered initialisation. The closure has already been moved out and consumed, so there is nothing left to retry with. std therefore marks the lock **poisoned**. Its documentation says that any thread that later tries to access it, through a dereference or `LazyLock::force`, **will panic**, and that this poisoning is **unrecoverable**: unlike `std::sync::Mutex`, there is no `PoisonError::into_inner` to get at a value. The panic message is "LazyLock instance has previously been poisoned"; for `LazyCell` it is "LazyCell instance has previously been poisoned". The `once_cell` crate's `Lazy` behaves the same way, so migrating to std does not change this. In a long-running service, this means one transient failure inside a global's closure (a missing file, a bad pattern) turns into a panic at **every** later access to that global, possibly in threads far from the original failure. ## A panic in an `OnceLock` initialiser: still empty `OnceLock::get_or_init` documents that if `f()` panics, the panic is propagated to the caller and **the cell remains uninitialised**. Its type-level documentation adds that, unlike `Mutex`, `OnceLock` is **never poisoned on panic**. The same holds for `OnceCell::get_or_init`. The next call, from the same thread after `catch_unwind` or from another thread, runs its own closure and may succeed. The code example demonstrates both outcomes side by side. | Type | Initialiser panics | Next access | |---|---|---| | `LazyLock` / `LazyCell` | panic propagates, lock poisoned | panics: "previously been poisoned" | | `OnceLock` / `OnceCell` | panic propagates, cell stays empty | `get` is `None`; `get_or_init` retries | ## Reentrant initialisation A different bug is an initialiser that, directly or indirectly, asks the **same cell** for its value before it has finished. std documents this as an error for both once types, with different consequences: 1. **`OnceCell::get_or_init`** panics with the message `reentrant init`. The inner call succeeds and fills the cell, then the outer call finds the cell already full; core's implementation panics there rather than silently returning the inner value, as a source comment explains. 2. **`OnceLock::get_or_init`**: std says the exact outcome is **unspecified**, that the current implementation **deadlocks**, and that this may change to a panic in future. The thread is waiting on a `Once` that it is itself holding. 3. **`LazyCell`** marks itself poisoned while its closure runs, precisely to stop reentrant access, so a closure that forces the same `LazyCell` panics with "LazyCell instance has previously been poisoned" and leaves it poisoned. 4. **`LazyLock`** waits on its internal `Once`, so a closure that dereferences its own static never returns: in a test on rustc 1.99.1, `static A: LazyLock<u32> = LazyLock::new(|| *A + 1);` simply hung. In every case the reentrant caller never observes a half-built value; it gets a panic or a hang instead of a wrong answer. This trap usually appears through **chains of globals**: `static A` is initialised from `B`, `B` is initialised from `C`, and `C` reads `A`. Nothing in the compiler detects such a cycle, because each closure is ordinary code. The symptom is a hang (with the Lock types) or a panic on first use (with the Cell types), often only on a code path that tests rarely exercise. ## Practical consequences - **Keep fallible work out of `LazyLock` closures** when the input comes from outside the program. Load in `main`, handle the `Result`, then store the value in an `OnceLock`. - **`unwrap` inside a `LazyLock` closure is acceptable** only when the failure is a programming error, such as a regex pattern written in the source, and a test forces the global once so the bug shows up in CI. - **Retrying is possible only with the once types.** A caller can wrap `get_or_init` in `std::panic::catch_unwind` and try again later; with a poisoned `LazyLock`, every retry panics again. - **Draw the dependency graph of lazy globals** in a code review. If any closure reaches back to its own static, through however many hops, it will deadlock or panic. ## Why interviewers ask it It is a production-diagnosis question with one right answer once the facts are known: a service where every request to one endpoint suddenly panics with "previously been poisoned", or a binary that hangs on start-up after a refactor of its globals. A strong candidate knows which type remembers a failure and which forgets it, and can recognise a reentrant initialisation from its symptoms.

  • Can a service recover from a poisoned `LazyLock` without restarting?
    Not through the `LazyLock`: std documents its poisoning as unrecoverable, with no `PoisonError::into_inner`-style escape hatch like a `Mutex` has. The process keeps panicking at every access. The practical fixes are moving fallible initialisation into an `OnceLock` that `main` fills, or restarting the process.
  • Why does `OnceCell` panic on reentrant initialisation instead of returning the inner value?
    When the outer closure returns, the inner call has already filled the cell, so the outer value cannot be stored. core chooses to panic with `reentrant init` rather than silently discard the outer result and hand back a value the caller did not compute, which would hide a logic error.

  • A LazyLock retries its closure after a panic
  • OnceLock is poisoned like a Mutex when the closure panics
  • A poisoned LazyLock can be recovered with into_inner
  • rustc detects cycles between lazy globals at compile time
  • Reentrant get_or_init on OnceLock just returns the inner value

Assumes Rust 1.99 on the 2024 edition; OnceCell and OnceLock are stable since 1.70 and LazyCell and LazyLock since 1.80, so older toolchains need the once_cell crate.