Patterncore
Lazy initialization
Also called lazy init, lazy loading, lazy holder, lazy value, deferred initialization, initialize on first use.
Lazy initialization creates an object or computes a value the first time a caller needs it, and stores the result for later calls. It saves work that a program may never need.
- Family
- creational-design
- Intent
- Delay the creation of an object or the computation of a value until the first time a caller needs it, and then keep the result for every later use.
- Also called
- Lazy Load, Initialize on Demand
Intent
Delay the creation of an object, or the computation of a value, until the first time a caller needs it. Then keep the result, so that every later use gets the same object without the cost.
Problem
A Settings object reads a configuration file. The read is slow, and many runs of the program never look at the configuration. If the constructor reads the file, every run pays for the read, and the start of the program is slower than it needs to be.
The .NET documentation gives the general case: defer the creation of a large or resource-intensive object, or a resource-intensive task, when it might not happen during the life of the program at all.1 The forces are these:
- The cost of the value is high, and some runs of the program do not need it.
- The value does not change after it is made, so one copy can serve all callers.
- The callers should not need to know whether the value exists yet.
Solution
Replace the field with an accessor. The accessor checks whether the value exists. If it does not, the accessor computes it and stores it. Then it returns the stored value.
Caller Settings.config() load()
------ ----------------- ------
config() -----------> stored? no -> lock -> stored? no -> ---> slow read
store result <-
<--------- return stored value
config() -----------> stored? yes -> return stored value
The participants are the holder, which owns the stored value and a flag or a lock, and the initializer, which computes the value. Most languages now have a holder in the standard library:
| Language | Holder | Thread-safe |
|---|---|---|
| Python | functools.cached_property; functools.cache for a function2 |
no, the getter can run more than once2 |
| JavaScript | a getter that replaces itself with a data property3 | one thread per agent |
| Java | a nested holder class for a static field45 | yes, by class initialization |
| C# | System.Lazy<T>1 |
yes, in the default mode1 |
| C++ | a function-local static6 |
yes, other threads wait6 |
| Go | sync.Once, sync.OnceValue7 |
yes |
| Rust | std::sync::OnceLock, std::sync::LazyLock89 |
yes; OnceCell and LazyCell are single-thread |
Thread safety. Two threads can both see that the value is missing, and both run the initializer. The result is two loads, or two objects where the program wanted one. A lock around the check and the store fixes this, but a lock on every read is slow. Double-checked locking reads without the lock first, and takes the lock only when the value is missing, then checks again.
The Double-Checked Locking is Broken declaration showed that this idiom does not work reliably in Java without more synchronization.4 Another thread can see the new reference before it sees the writes that built the object. Under the memory model of JDK 5 and later, a volatile field fixes the idiom, because a write to a volatile field cannot be reordered with an earlier read or write.4 The Java example uses this form.
For a static value, Java has a simpler form. The language initializes a class just before the first use of one of its static fields, and class initialization is thread-safe.5 So a nested class with one static field is a lazy holder with no lock in the code. The declaration gives this as the solution for static singletons.4 Effective Java recommends this lazy initialization holder class idiom for a static field, and double-checked locking for an instance field.10
C++ gives the same guarantee for a function-local static. If a thread reaches the declaration while another thread is initializing the variable, it waits until the initialization completes.6
Example
The example files show one program in each language. Settings loads its configuration on the first call. The program reads the value twice, and the load runs once. Then eight threads ask a new Settings for its value at the same time, and the load still runs once:
| Language | Form |
|---|---|
| Python | a property with double-checked locking and threading.Lock |
| JavaScript | a self-overwriting getter, and a cached promise for the async case |
| TypeScript | a generic lazy<T> closure, and a cached promise |
| Java | double-checked locking with a volatile field |
| C# | Lazy<T> in its default thread-safe mode |
| C++ | std::call_once with a std::once_flag |
| Go | sync.OnceValue |
| Rust | OnceLock::get_or_init |
In JavaScript, a synchronous value has no race, but an asynchronous load does. A second caller can ask while the first load is still running. The fix is to store the promise, not the result, so that every caller waits for the same load.
import threading
class Settings:
def __init__(self):
self._config = None
self._lock = threading.Lock()
self.loads = 0
def _load(self) -> dict:
print("loading config") # stands for a slow read of a file
self.loads += 1
return {"timeout": 30}
@property
def config(self) -> dict:
if self._config is None: # fast path: no lock after the first load
with self._lock:
if self._config is None: # check again under the lock
self._config = self._load()
return self._config
s = Settings()
print("settings created, loads =", s.loads)
print("timeout =", s.config["timeout"])
print("timeout =", s.config["timeout"])
print("loads =", s.loads)
shared = Settings()
start = threading.Barrier(8)
def worker():
start.wait() # all eight threads ask at the same time
shared.config
threads = [threading.Thread(target=worker) for _ in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
print("8 threads: loads =", shared.loads)
settings created, loads = 0
loading config
timeout = 30
timeout = 30
loads = 1
loading config
8 threads: loads = 1
- Verdict: stdlib.
functools.cached_propertycomputes a value on first access and stores it as a normal attribute. Its documentation says that it does not prevent a race, so the getter can run more than once on one instance. The example uses a lock for that reason. functools.cachemakes a function lazy and memoized: the first call computes, and later calls with the same arguments return the stored result.- A module is a lazy singleton: Python runs its code at the first
importand caches the module object.
#include <atomic>
#include <iostream>
#include <map>
#include <mutex>
#include <string>
#include <thread>
#include <vector>
class Settings {
public:
const std::map<std::string, int>& config() {
std::call_once(once_, [this] { config_ = load(); }); // runs on one thread only
return config_;
}
int loads() const { return loads_; }
private:
std::map<std::string, int> load() {
std::cout << "loading config\n"; // stands for a slow read of a file
++loads_;
return {{"timeout", 30}};
}
std::once_flag once_;
std::map<std::string, int> config_;
std::atomic<int> loads_{0};
};
int main() {
Settings s;
std::cout << "settings created, loads = " << s.loads() << "\n";
int first = s.config().at("timeout"); // load before the line is printed
std::cout << "timeout = " << first << "\n";
std::cout << "timeout = " << s.config().at("timeout") << "\n";
std::cout << "loads = " << s.loads() << "\n";
Settings shared;
std::atomic<bool> go{false};
std::vector<std::thread> threads;
for (int i = 0; i < 8; ++i) {
threads.emplace_back([&] {
while (!go.load()) std::this_thread::yield(); // all eight ask at the same time
shared.config();
});
}
go = true;
for (auto& t : threads) t.join();
std::cout << "8 threads: loads = " << shared.loads() << "\n";
}
settings created, loads = 0
loading config
timeout = 30
timeout = 30
loads = 1
loading config
8 threads: loads = 1
- Verdict: stdlib.
std::call_oncewith astd::once_flagruns a function once, even when many threads call it together. - For a single global value, a function-local
staticis simpler. The language initializes it on the first pass through its declaration, and a thread that enters while another initializes it waits. std::optional<T>holds a lazy value in a single thread with no lock.
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
static final class Settings {
private volatile Map<String, Integer> config; // volatile makes the check safe
final AtomicInteger loads = new AtomicInteger();
private Map<String, Integer> load() {
System.out.println("loading config"); // stands for a slow read of a file
loads.incrementAndGet();
return Map.of("timeout", 30);
}
Map<String, Integer> config() {
Map<String, Integer> result = config; // read the volatile field once
if (result == null) {
synchronized (this) {
result = config;
if (result == null) { // check again under the lock
config = result = load();
}
}
}
return result;
}
}
public static void main(String[] args) throws InterruptedException {
Settings s = new Settings();
System.out.println("settings created, loads = " + s.loads.get());
System.out.println("timeout = " + s.config().get("timeout"));
System.out.println("timeout = " + s.config().get("timeout"));
System.out.println("loads = " + s.loads.get());
Settings shared = new Settings();
CountDownLatch start = new CountDownLatch(1);
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < 8; i++) {
Thread t = new Thread(() -> {
try {
start.await(); // all eight threads ask at the same time
} catch (InterruptedException e) {
return;
}
shared.config();
});
t.start();
threads.add(t);
}
start.countDown();
for (Thread t : threads) {
t.join();
}
System.out.println("8 threads: loads = " + shared.loads.get());
}
}
settings created, loads = 0
loading config
timeout = 30
timeout = 30
loads = 1
loading config
8 threads: loads = 1
- Verdict: idiom. This is double-checked locking with a
volatilefield, the form of Effective Java Item 83 for an instance field. Withoutvolatile, another thread can see the reference before it sees the fields of the object. - For a static field, the lazy initialization holder class idiom is simpler. The JVM initializes a class only on first use, and class initialization is thread-safe, so a nested class with one static field needs no lock.
java.util.function.Supplieris the usual type for a lazy value that a caller passes in.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
sealed class Settings
{
private readonly Lazy<Dictionary<string, int>> config;
private int loads;
public int Loads => Volatile.Read(ref loads);
public Settings() =>
// The default mode, ExecutionAndPublication, runs Load on one thread only.
config = new Lazy<Dictionary<string, int>>(Load);
private Dictionary<string, int> Load()
{
Console.WriteLine("loading config"); // stands for a slow read of a file
Interlocked.Increment(ref loads);
return new Dictionary<string, int> { ["timeout"] = 30 };
}
public Dictionary<string, int> Config => config.Value;
}
static class Program
{
static void Main()
{
var s = new Settings();
Console.WriteLine($"settings created, loads = {s.Loads}");
Console.WriteLine($"timeout = {s.Config["timeout"]}");
Console.WriteLine($"timeout = {s.Config["timeout"]}");
Console.WriteLine($"loads = {s.Loads}");
var shared = new Settings();
using var start = new ManualResetEventSlim(false);
var tasks = Enumerable.Range(0, 8)
.Select(i => Task.Run(() => { start.Wait(); _ = shared.Config; }))
.ToArray();
start.Set(); // all eight tasks ask at the same time
Task.WaitAll(tasks);
Console.WriteLine($"8 threads: loads = {shared.Loads}");
}
}
settings created, loads = 0
loading config
timeout = 30
timeout = 30
loads = 1
loading config
8 threads: loads = 1
- Verdict: stdlib.
System.Lazy<T>wraps a factory and runs it on the first read ofValue. TheLazyThreadSafetyModeargument picks one thread, a race where the first result wins, or no thread safety. - With a factory,
Lazy<T>caches an exception: if the first call throws, later reads ofValuethrow the same exception. LazyInitializer.EnsureInitializedgives the same behaviour for a plain field, with no wrapper object.
let loads = 0;
function loadConfig() {
console.log("loading config"); // stands for a slow read of a file
loads += 1;
return { timeout: 30 };
}
const settings = {
// A getter that replaces itself with a plain property on first access.
get config() {
const value = loadConfig();
Object.defineProperty(this, "config", { value, writable: false });
return value;
},
};
console.log("settings created, loads =", loads);
console.log("timeout =", settings.config.timeout);
console.log("timeout =", settings.config.timeout);
console.log("loads =", loads);
// For an async value, cache the promise, not the result, so that callers
// that ask at the same time share one load.
let asyncLoads = 0;
let pending = null;
function config() {
pending ??= new Promise((resolve) => {
asyncLoads += 1;
setTimeout(() => resolve({ timeout: 30 }), 10);
});
return pending;
}
const callers = Array.from({ length: 8 }, () => config());
Promise.all(callers).then(() => console.log("8 callers: loads =", asyncLoads));
settings created, loads = 0
loading config
timeout = 30
timeout = 30
loads = 1
8 callers: loads = 1
- Verdict: idiom. MDN calls this form a smart, self-overwriting or lazy getter: the getter computes the value, then defines a data property with the same name.
- JavaScript runs one thread per agent, so a synchronous lazy value needs no lock. An asynchronous load does have a race: a second caller can ask before the first load ends. Store the promise to close it.
- ES modules are evaluated once, at the first import, and dynamic
import()loads a module only when the program asks for it.
// lazy returns a function that runs init once and then returns the stored value.
function lazy<T>(init: () => T): () => T {
let done = false;
let value: T | undefined;
return () => {
if (!done) {
value = init();
done = true;
}
return value as T;
};
}
let loads = 0;
class Settings {
readonly config = lazy(() => {
console.log("loading config"); // stands for a slow read of a file
loads += 1;
return { timeout: 30 };
});
}
const s = new Settings();
console.log("settings created, loads =", loads);
console.log("timeout =", s.config().timeout);
console.log("timeout =", s.config().timeout);
console.log("loads =", loads);
// An async value: the stored value is the promise, so callers share one load.
let asyncLoads = 0;
const remote = lazy(
() =>
new Promise<{ timeout: number }>((resolve) => {
asyncLoads += 1;
setTimeout(() => resolve({ timeout: 30 }), 10);
}),
);
Promise.all(Array.from({ length: 8 }, () => remote())).then(() =>
console.log("8 callers: loads =", asyncLoads),
);
settings created, loads = 0
loading config
timeout = 30
timeout = 30
loads = 1
8 callers: loads = 1
- Verdict: idiom. A closure over a flag and a value is a typed lazy holder. The flag, not a test for
undefined, records that the value exists, soinitcan returnundefinedand still run once. - The same
lazyworks for a promise, which gives a shared async load.
package main
import (
"fmt"
"sync"
"sync/atomic"
)
type Settings struct {
Config func() map[string]int
loads atomic.Int32
}
func NewSettings() *Settings {
s := &Settings{}
// OnceValue returns a function that calls load only once, even when
// many goroutines call it at the same time.
s.Config = sync.OnceValue(func() map[string]int {
fmt.Println("loading config") // stands for a slow read of a file
s.loads.Add(1)
return map[string]int{"timeout": 30}
})
return s
}
func main() {
s := NewSettings()
fmt.Println("settings created, loads =", s.loads.Load())
fmt.Println("timeout =", s.Config()["timeout"])
fmt.Println("timeout =", s.Config()["timeout"])
fmt.Println("loads =", s.loads.Load())
shared := NewSettings()
start := make(chan struct{})
var wg sync.WaitGroup
for range 8 {
wg.Add(1)
go func() {
defer wg.Done()
<-start // all eight goroutines ask at the same time
shared.Config()
}()
}
close(start)
wg.Wait()
fmt.Println("8 goroutines: loads =", shared.loads.Load())
}
settings created, loads = 0
loading config
timeout = 30
timeout = 30
loads = 1
loading config
8 goroutines: loads = 1
- Verdict: stdlib.
sync.Onceruns an action exactly once, andsync.OnceValuewraps a function that returns a value. If the function panics, every call panics with the same value. - A package-level variable is initialized before
mainruns, so it is not lazy. Usesync.OnceValuefor a global that is costly and may not be needed.
use std::collections::HashMap;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Barrier, OnceLock};
use std::thread;
struct Settings {
config: OnceLock<HashMap<&'static str, u32>>,
loads: AtomicUsize,
}
impl Settings {
fn new() -> Settings {
Settings { config: OnceLock::new(), loads: AtomicUsize::new(0) }
}
fn config(&self) -> &HashMap<&'static str, u32> {
// get_or_init runs the closure once; other threads wait for it.
self.config.get_or_init(|| {
println!("loading config"); // stands for a slow read of a file
self.loads.fetch_add(1, Ordering::SeqCst);
HashMap::from([("timeout", 30)])
})
}
fn loads(&self) -> usize {
self.loads.load(Ordering::SeqCst)
}
}
fn main() {
let s = Settings::new();
println!("settings created, loads = {}", s.loads());
println!("timeout = {}", s.config()["timeout"]);
println!("timeout = {}", s.config()["timeout"]);
println!("loads = {}", s.loads());
let shared = Settings::new();
let start = Barrier::new(8);
thread::scope(|scope| {
for _ in 0..8 {
scope.spawn(|| {
start.wait(); // all eight threads ask at the same time
shared.config();
});
}
});
println!("8 threads: loads = {}", shared.loads());
}
settings created, loads = 0
loading config
timeout = 30
timeout = 30
loads = 1
loading config
8 threads: loads = 1
- Verdict: stdlib.
std::sync::OnceLockis a cell that can be written once, safe for many threads.std::sync::LazyLockholds the closure as well, and runs it on the first dereference. std::cell::OnceCellandLazyCellare the single-thread versions, with no synchronization cost.- The type system marks the difference: a
OnceCellis notSync, so the compiler rejects code that shares it between threads.
Consequences
The benefits are a faster start and less work. A value that no caller needs is never computed, and a value that many callers need is computed once.
The costs:
- The first caller pays. The cost moves from the start of the program to the first use, which can be in the middle of a request that must be fast. If that is a problem, initialize the value at the start.
- Every access pays a check. Each read tests a flag, and a thread-safe holder may need a memory barrier. Effective Java warns that lazy initialization lowers the cost of creating the object but raises the cost of each access, and that in most cases normal initialization is better.10
- Errors come later. A bad configuration file is found at the first use, not at the start. The holder must also decide what a failed initialization means.
Lazy<T>with a factory caches the exception: if the factory throws the first time, every later read ofValuethrows the same exception.1 Go'ssync.OnceValuepanics with the same value on every call if the function panics.7 Rust'sLazyLockis poisoned if its closure panics, and later accesses panic.8 - Order becomes hidden. The program no longer says when the value is made. A lazy value that depends on another lazy value can form a cycle, and in C++ a recursive entry into the initialization of a
staticis undefined behaviour.6
The marker of "not yet" must not be a valid value. A hand-written holder often uses None or null for "not computed". If the initializer can return that value, the holder computes it again on every call:
This code runs but gives a wrong answer on purpose.
class Settings:
def __init__(self):
self._proxy = None
self.loads = 0
@property
def proxy(self):
if self._proxy is None: # None means "not loaded", but it is also a result
self.loads += 1
self._proxy = None # no proxy is configured
return self._proxy
s = Settings()
for _ in range(3):
s.proxy
print("loads:", s.loads)
loads: 3
Use a separate flag, a private sentinel object, or a holder from the standard library. functools.cached_property stores the result as a normal attribute, so it works for None:2
from functools import cached_property
class Settings:
def __init__(self):
self.loads = 0
@cached_property
def proxy(self):
self.loads += 1
return None # no proxy is configured
s = Settings()
for _ in range(3):
s.proxy
print("loads:", s.loads)
loads: 1
When not to use it
Do not make a value lazy when it is cheap, or when every run needs it. The check on each access is a cost with no gain. Effective Java gives the rule as: do not do it unless you need to.10
Do not use lazy initialization to hide a slow start that should be fixed. If the first request of every user waits for the load, the program is not faster, only less predictable.
Do not write your own thread-safe holder when the language has one. Double-checked locking is easy to get wrong, and the declaration shows that its correctness depends on the memory model of the language.4
Variants and related patterns
Lazy Load. Fowler's Lazy Load is an object that does not contain all of the data you need but knows how to get it.11 It applies lazy initialization to data from a database, in four forms: lazy initialization, virtual proxy, value holder and ghost.
Virtual proxy. A Proxy pattern that stands in for a costly object and creates it on the first call. The caller sees the interface of the real object, not a holder.
Memoization. functools.cache makes a function lazy for each argument: the first call with an argument computes the result, and later calls return the stored result.2 Lazy initialization is memoization of a function with no arguments.
Lazy singleton. A Singleton pattern that creates its instance on first access is lazy initialization of a global. The holder class idiom in Java and a function-local static in C++ are the safe forms.
Lazy evaluation. Some languages delay the evaluation of every expression until its value is needed. Lazy initialization is the same idea for one value, written by hand in a language that evaluates eagerly.
Known uses
- Go: mime/type.go at go1.25.0 builds its table of MIME types lazily. A package-level
sync.OnceguardsinitMime, andTypeByExtensioncallsonce.Do(initMime)before it reads the table, so a program that never asks for a MIME type never builds it.12
References
- Lazy<T> Class, .NET API reference, Remarks (the purpose of lazy initialization; thread safety; exception caching)
- The Python Standard Library, functools, Python 3.14, cached_property; cache
- get, MDN Web Docs, Smart / self-overwriting / lazy getters
- The "Double-Checked Locking is Broken" Declaration, the signers; introduction; Fixing Double-Checked Locking using Volatile; Making it work for static singletons
- The Java Language Specification, Java SE 25 Edition, 12.4.1 When Initialization Occurs
- Working Draft, Programming Languages, C++ (N4950), [stmt.dcl] paragraph 3 (block variables with static storage duration)
- Package sync, the Go standard library, type Once; func OnceValue
- LazyLock, The Rust Standard Library, Description; Poisoning
- OnceLock, The Rust Standard Library, Description
- Joshua Bloch, Effective Java, third edition, Addison-Wesley, 2018, Item 83, Use lazy initialization judiciously
- Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 11, Object-Relational Behavioral Patterns, Lazy Load
- Go go1.25.0 source, src/mime/type.go, once, initMime and TypeByExtension, lines 72 to 105
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 4XE8YW Edit this page History Report an error Markdown