skip to content

In Rust, why does rustc reject a `static` of type `LazyCell` or `OnceCell` but accept `LazyLock` and `OnceLock`, and when is each pair the right choice?

level: middleimportance: should knowfreq 30%

answer

  1. statics are shared by all threads
  2. Sync is the gate
  3. E0277 names the missing trait
  4. thread_local or struct fields

basics

~20 s

A shared static must be Sync. LazyCell and OnceCell are not, so rustc reports E0277; LazyLock and OnceLock synchronise the first write and are Sync for Send + Sync values. Use the Lock pair for globals and the Cell pair on one thread.

solid answer

~40 s

A `static` can be read from any thread, so rustc requires its type to implement `Sync` and reports **E0277** ("`OnceCell<String>` cannot be shared between threads safely", with the note "shared static variables must have a type that implements `Sync`") otherwise. `std::cell::OnceCell` and `LazyCell` do no synchronisation, so they are not `Sync`; `OnceCell` even carries an explicit `!Sync` impl, and rustc's note suggests `std::sync::OnceLock`. `OnceLock` and `LazyLock` guard the first write with a `std::sync::Once`, so they are `Sync` when `T: Send + Sync`. Pick the Lock pair for statics and for values shared across threads; pick the Cell pair for struct fields used on one thread and inside `thread_local!`, where the synchronisation would be wasted. The wrapper never makes `T` itself shareable: `LazyLock<Cell<u32>>` in a static still fails with E0277.

code

rust · 7 lines
rust
use std::cell::{Cell, OnceCell};
use std::sync::LazyLock;

static NAME: OnceCell<String> = OnceCell::new();
static HITS: LazyLock<Cell<u32>> = LazyLock::new(|| Cell::new(0));

fn main() {}

go deeper

for a junior

Remember the rule of thumb: types from std::sync go in statics, types from std::cell stay on one thread.

for a middle

Explain that statics must be Sync, why an unsynchronised first write would be a data race, and read the E0277 note that names the missing Sync bound.

for a senior

Point out that the wrapper protects initialisation only, so LazyLock<Cell<u32>> still fails, and choose the Cell types deliberately for thread_local! and single-threaded fields.

for a principal

Use the choice as documentation: a Cell type makes the owning struct !Sync, so the compiler enforces the single-thread assumption for every future change.

## Four types, two axes Since **Rust 1.70** (`OnceCell`, `OnceLock`) and **Rust 1.80** (`LazyCell`, `LazyLock`), std has four once-initialised types. They differ along two independent axes: | | Initialiser given at the call site | Initialiser stored at construction | |---|---|---| | **Single-threaded** (`std::cell`) | `OnceCell<T>` | `LazyCell<T, F>` | | **Thread-safe** (`std::sync`) | `OnceLock<T>` | `LazyLock<T, F>` | The "once" types take the closure when you call `get_or_init`, so the caller can pass in data. The "lazy" types take the closure in `new` and run it on the first dereference, so they look like a plain `&T` afterwards. This question is about the other axis: **Cell versus Lock**. ## Why a `static` must be `Sync` A `static` item is a single value shared by the whole program. Any thread may take a `&` reference to it, at any time. Rust expresses "a shared reference to this may cross threads" as the auto trait **`Sync`**, and rustc enforces it on every shared static. The diagnostic is **E0277**, and for a `static NAME: OnceCell<String>` rustc 1.99.1 prints: - the error line "`OnceCell<String>` cannot be shared between threads safely"; - a note suggesting `std::sync::OnceLock` instead; - the note "shared static variables must have a type that implements `Sync`". For `LazyCell` the message names the inner `UnsafeCell` that makes it non-`Sync`, followed by "required because it appears within the type `LazyCell<...>`". ## Why the Cell types are not `Sync` `OnceCell` and `LazyCell` store their value in an `UnsafeCell` and write it on first use **without any atomic operation or lock**. If two threads called `get_or_init` at once, both could see an empty cell and write simultaneously, which is a data race. So the Cell types are designed for one thread: `OnceCell<T>` has an explicit `impl<T> !Sync for OnceCell<T>` in core, and `LazyCell` is non-`Sync` because of its `UnsafeCell`. In exchange they are as cheap as a branch on a discriminant. ## What the Lock types add `OnceLock` and `LazyLock` wrap the same idea around a `std::sync::Once`: - **Exactly one thread runs the initialiser.** For `OnceLock::get_or_init`, std guarantees that only one closure runs if it does not panic, even when several threads call it concurrently with different closures. - **Others wait.** A thread that arrives while initialisation is in progress blocks until the value is stored. `OnceLock::wait` (Rust 1.86) blocks until some other code fills the cell. - **They are `Sync` under conditions.** `OnceLock<T>` is `Sync` when `T: Sync + Send`; `LazyLock<T, F>` when `T: Sync + Send` and `F: Send`. Requiring `Send` too matters: the value is created on one thread and may be dropped, or taken, on another. The wrapper only protects the **initialisation**. It does not make the inner value shareable. A `static HITS: LazyLock<Cell<u32>>` still fails with E0277, because `Cell<u32>` is not `Sync`; rustc points you at a lock or an atomic for mutation, which is the material on threads and atomics. ## Choosing between the pairs Use the **Lock** pair when: - the value lives in a `static`; - the value is shared across threads by other means, such as inside an `Arc`; - you need to block until another thread provides it (`OnceLock::wait`). Use the **Cell** pair when: 1. the value is a field of a struct that never leaves one thread, such as a cached parse of a settings file; 2. the value lives inside `thread_local!`, where each thread already has its own copy; 3. you are in `no_std` code without `std::sync` available, because `OnceCell` and `LazyCell` live in `core::cell`. Choosing the Cell type also documents intent: the compiler will stop anyone from sharing the struct across threads by accident, because the struct inherits `!Sync`. ## Cost The Cell types check an enum tag or an `Option` on every access. The Lock types check the `Once` state with an atomic load on every access, and on the first access may block. Both are cheap after initialisation, but the Lock types add synchronisation a single-threaded value never needs, which is why std keeps both pairs. ## Why interviewers ask it The question tests whether a candidate can predict a real compile error from the type's thread-safety, read the E0277 diagnostic, and pick the right member of the family without defaulting to the thread-safe one everywhere.

  • Does wrapping a type in `LazyLock` make it safe to share between threads?
    No. `LazyLock` only synchronises the one-time initialisation. It is `Sync` only when `T: Send + Sync`, so `LazyLock<Cell<u32>>` or `LazyLock<Rc<String>>` in a static still fails with E0277. Shared mutation needs a lock or an atomic inside it.
  • Why does `OnceLock<T>` require `T: Send` as well as `T: Sync` to be `Sync`?
    Any thread holding `&OnceLock<T>` can call `set` or `get_or_init` and create the value there, and the value may later be used or dropped from a different thread. Moving a value's ownership between threads is what `Send` permits, so std requires both.

  • OnceCell is fine in a static because it is only written once
  • LazyLock makes any inner type thread-safe
  • Always use the Lock types, the Cell types are obsolete
  • The E0277 error means LazyCell::new is not const
  • LazyCell and LazyLock differ only in performance

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.