Programming Search⌘K

Patterncore

Singleton pattern

Also called Singleton.

A class makes sure that it has only one instance, and gives the whole program one global way to reach it. The global access causes most of the problems of the pattern.

Family
creational-design
Intent
Make sure that a class has only one instance, and give one global point of access to it.
Refactorings
Inline singleton, Limit instantiation with singleton

Intent

Make sure that a class has only one instance, and give one global point of access to it.1

The intent has two parts, and they are different things. The first part is a constraint on the number of instances. The second part is a way to find the instance from anywhere. Most of the debate about the pattern is about the second part.

Problem

Some things exist once in a running program. There is one configuration that the program read at start, one connection pool for a database, one table of loaded plugins. Design Patterns gives a printer spooler, a file system and a window manager as examples.1 Two parts of the program can each make their own configuration object. Then a change made through one object does not show in the other, and the program reads the files twice.

The forces are these. There must be exactly one instance, and the type must enforce this, not a comment. Code in many places needs the instance, and it is not always convenient to pass it down. The instance can be expensive to create, so it should be created on first use, not at start. And in a program with threads, two threads that need it at the same moment must get the same instance.

Solution

The class takes over the job of creating its instance. Its constructor is private, so no other code can call it. A static field holds the one instance, and a static operation returns it, and creates it on the first call.1

 Settings
 ------------------------------------------
 - instance: Settings   (static)
 - Settings()           (private constructor)
 + get(): Settings      (static)
     if instance is empty: instance = new Settings()
     return instance
 + level, set_level(...)  (the actual job of the class)

The participant is the Singleton class itself. Clients reach the instance only through the static operation.1 The class therefore has two jobs: its own work, and the control of its life cycle.

Most languages have a construct that gives the single instance with less code. The construct also solves the thread problem, because the runtime guarantees that the initialization runs once:

Language Construct Guarantee
Python a module a module runs once; later imports get the same object from sys.modules1314
JavaScript an ES module the host returns the same module record for the same request1718
Kotlin an object declaration initialization is thread-safe and done on first access19
Java a static field of a nested holder class, or an enum with one constant class initialization runs once, under a lock1112
C# a static constructor, or Lazy<T> a static constructor runs at most once; Lazy<T> is thread-safe by default2021
Go a package-level variable, or sync.OnceValue a package is initialized once; OnceValue calls its function once2223
Rust a static with LazyLock initialized on first access, and other threads block until it is done24
C++ a function-local static initialized the first time control passes the declaration; concurrent callers wait26

The Python FAQ states it directly. There is only one instance of each module, and a module is also the basis for the singleton design pattern.13 Norvig makes a similar point for dynamic languages: memoization of the creation function gives the same effect.8

Example

The example files show one program in each language. A Settings object prints "creating the settings" when it is created. The main code reads the level, info. A worker, on a second thread where the language has threads, gets the settings, and sets the level to debug. The main code reads the level again and sees debug, and the program checks that both got the same instance. The creation message appears once.

Language Form
Python a module, settings.py, imported by the main module and by the worker
JavaScript an ES module, imported statically by main.js and dynamically by the worker
TypeScript a class with a private constructor and a static accessor
Java the holder class idiom
Kotlin an object declaration
C# a Lazy<T> in a static field
Go sync.OnceValue
Rust static LazyLock<Mutex<Settings>>
C++ a function-local static in a static member function
PythonGitHub
print("creating the settings")

level = "info"
import threading

import settings

seen = []


def worker():
    # A second import finds the module in sys.modules and does not run it again.
    import settings as again

    print("worker sets debug")
    again.level = "debug"
    seen.append(again)


print(f"main: {settings.level}")
thread = threading.Thread(target=worker)
thread.start()
thread.join()
print(f"main: {settings.level}")
print(f"same instance: {seen[0] is settings}")
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: True
  • Verdict: native. A module is the singleton. Python runs a module once and stores it in sys.modules. Every later import returns the same module object.
  • The import lock makes the first import safe when two threads import the module at the same time.
  • The module runs when it is first imported. To create an expensive object on first use, the module can hold a function that creates and stores it, protected by a lock.
  • Code that runs settings.py as a script gets a second copy, named __main__, separate from the copy that import settings makes.
#include <iostream>
#include <mutex>
#include <string>
#include <thread>
#include <utility>

class Settings {
public:
    static Settings& instance() {
        // Initialized the first time control passes here; concurrent callers wait.
        static Settings settings;
        return settings;
    }

    Settings(const Settings&) = delete;
    Settings& operator=(const Settings&) = delete;

    std::string level() const {
        std::lock_guard lock(mutex_);
        return level_;
    }

    void set_level(std::string level) {
        std::lock_guard lock(mutex_);
        level_ = std::move(level);
    }

private:
    Settings() { std::cout << "creating the settings\n"; }

    mutable std::mutex mutex_;
    std::string level_ = "info";
};

int main() {
    Settings& first = Settings::instance();
    std::cout << "main: " << first.level() << "\n";
    const Settings* seen = nullptr;
    std::thread worker([&seen] {
        Settings& settings = Settings::instance();
        std::cout << "worker sets debug\n";
        settings.set_level("debug");
        seen = &settings;
    });
    worker.join();
    std::cout << "main: " << Settings::instance().level() << "\n";
    std::cout << "same instance: " << std::boolalpha << (seen == &first) << "\n";
}
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: true
  • Verdict: idiom. A function-local static is the usual C++ singleton. The standard makes its initialization run once, and makes concurrent callers wait for it.
  • The deleted copy constructor and copy assignment stop code from making a copy of the instance.
  • A global object at namespace scope would be the eager form, but its dynamic initialization is not ordered with globals in other translation units. The function-local static avoids that order problem.
  • The object is destroyed at exit, in reverse order of construction. A singleton that uses another singleton in its destructor can see an object that is already destroyed.
JavaGitHub
public class Main {
    static final class Settings {
        private volatile String level = "info";

        private Settings() {
            System.out.println("creating the settings");
        }

        // The JVM initializes Holder once, on the first call to get().
        private static final class Holder {
            static final Settings INSTANCE = new Settings();
        }

        static Settings get() {
            return Holder.INSTANCE;
        }

        String level() {
            return level;
        }

        void setLevel(String level) {
            this.level = level;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Settings first = Settings.get();
        System.out.println("main: " + first.level());
        Settings[] seen = new Settings[1];
        Thread worker = new Thread(() -> {
            Settings settings = Settings.get();
            System.out.println("worker sets debug");
            settings.setLevel("debug");
            seen[0] = settings;
        });
        worker.start();
        worker.join();
        System.out.println("main: " + Settings.get().level());
        System.out.println("same instance: " + (seen[0] == first));
    }
}
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: true
  • Verdict: idiom. The holder class idiom: the class Holder is initialized the first time code reads Holder.INSTANCE, and the JVM runs that initialization once, under a lock. It needs no explicit locking.
  • An enum with one constant, enum Settings { INSTANCE; ... }, is the other usual form. It also resists reflection and serialization, as the node page shows.
  • The field level is volatile, so a change by one thread is visible to the others. The single instance does not make its own state thread-safe.
Settings first = Settings.Instance;
Console.WriteLine($"main: {first.Level}");
Settings? seen = null;
var worker = new Thread(() =>
{
    Settings settings = Settings.Instance;
    Console.WriteLine("worker sets debug");
    settings.Level = "debug";
    seen = settings;
});
worker.Start();
worker.Join();
Console.WriteLine($"main: {Settings.Instance.Level}");
Console.WriteLine($"same instance: {ReferenceEquals(seen, first)}");

sealed class Settings
{
    private static readonly Lazy<Settings> instance = new(() => new Settings());

    public static Settings Instance => instance.Value;

    private volatile string level = "info";

    private Settings()
    {
        Console.WriteLine("creating the settings");
    }

    public string Level
    {
        get => level;
        set => level = value;
    }
}
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: True
  • Verdict: stdlib. Lazy<T> creates the value on the first read of Value. Its default mode is thread-safe: only one thread runs the factory, and the others wait for it.
  • A static field with an initializer, static readonly Settings Instance = new();, is the shorter form. The runtime runs static initialization at most once, but it is less precise about when.
  • In an application that uses Microsoft.Extensions.DependencyInjection, register the class with AddSingleton instead, and take it as a constructor parameter.
JavaScriptGitHub
console.log("creating the settings");

export const settings = { level: "info" };
import { settings } from "./settings.mjs";

async function worker() {
  // A second import of the same specifier gets the same module.
  const { settings: again } = await import("./settings.mjs");
  console.log("worker sets debug");
  again.level = "debug";
  return again;
}

console.log(`main: ${settings.level}`);
const seen = await worker();
console.log(`main: ${settings.level}`);
console.log(`same instance: ${seen === settings}`);
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: true
  • Verdict: native. An ES module is evaluated once, and every import of the same specifier from the same place gets the same module. So the exported object is the single instance.
  • The module runs when the program first imports it, not on first use. A module that must create its object lazily exports a function that creates and stores it on the first call.
  • JavaScript runs one thread for this code, so there is no race on creation. Worker threads each load their own copy of the module, with their own instance.
  • The settings binding is const, but the object is not frozen. Object.freeze gives a read-only singleton.
TypeScriptGitHub
class Settings {
  static #instance: Settings | undefined;

  level = "info";

  private constructor() {
    console.log("creating the settings");
  }

  static get instance(): Settings {
    Settings.#instance ??= new Settings();
    return Settings.#instance;
  }
}

function worker(): Settings {
  const settings = Settings.instance;
  console.log("worker sets debug");
  settings.level = "debug";
  return settings;
}

const first = Settings.instance;
console.log(`main: ${first.level}`);
const seen = worker();
console.log(`main: ${Settings.instance.level}`);
console.log(`same instance: ${seen === first}`);
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: true
  • Verdict: idiom. The classic form: a private constructor and a static accessor that creates the instance on first use with ??=.
  • private is a compile-time check. After the types are stripped, JavaScript code can still call new Settings(). The #instance field is private at run time too.
  • An exported object from an ES module is the more usual TypeScript form, as the JavaScript example shows.
package main

import (
	"fmt"
	"sync"
)

type Settings struct {
	mu    sync.Mutex
	level string
}

func (s *Settings) Level() string {
	s.mu.Lock()
	defer s.mu.Unlock()
	return s.level
}

func (s *Settings) SetLevel(level string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.level = level
}

// GetSettings calls the function once, on the first call, even from many goroutines.
var GetSettings = sync.OnceValue(func() *Settings {
	fmt.Println("creating the settings")
	return &Settings{level: "info"}
})

func main() {
	first := GetSettings()
	fmt.Println("main:", first.Level())
	var seen *Settings
	var wg sync.WaitGroup
	wg.Go(func() {
		settings := GetSettings()
		fmt.Println("worker sets debug")
		settings.SetLevel("debug")
		seen = settings
	})
	wg.Wait()
	fmt.Println("main:", GetSettings().Level())
	fmt.Println("same instance:", seen == first)
}
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: true
  • Verdict: stdlib. sync.OnceValue wraps a function so that it runs once, and returns its result to every caller. Concurrent callers wait for the first call to finish.
  • A package-level variable, var settings = &Settings{level: "info"}, is the eager form. Go initializes each package once, before main runs.
  • The mutex protects the state of the instance. OnceValue only protects its creation.
  • sync.WaitGroup.Go starts the goroutine and adds it to the group in one call.
RustGitHub
use std::sync::{LazyLock, Mutex};
use std::thread;

struct Settings {
    level: String,
}

// Initialized on first access; other threads block until it is done.
static SETTINGS: LazyLock<Mutex<Settings>> = LazyLock::new(|| {
    println!("creating the settings");
    Mutex::new(Settings {
        level: "info".to_string(),
    })
});

fn address() -> usize {
    let settings: &Mutex<Settings> = &SETTINGS;
    settings as *const Mutex<Settings> as usize
}

fn main() {
    println!("main: {}", SETTINGS.lock().unwrap().level);
    let worker = thread::spawn(|| {
        println!("worker sets debug");
        SETTINGS.lock().unwrap().level = "debug".to_string();
        address()
    });
    let seen = worker.join().unwrap();
    println!("main: {}", SETTINGS.lock().unwrap().level);
    println!("same instance: {}", seen == address());
}
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: true
  • Verdict: stdlib. std::sync::LazyLock runs its closure on the first access and stores the value. A static of that type is the single instance.
  • A static must be Sync, so mutable state needs a lock such as Mutex. A static mut would compile only with unsafe at every use.
  • OnceLock is the variant that is set once at run time with a value that the program computes, such as configuration read in main.
  • A static is never dropped, so its destructor does not run at exit.
KotlinGitHub
import kotlin.concurrent.thread

object Settings {
    init {
        println("creating the settings")
    }

    @Volatile
    var level = "info"
}

fun main() {
    val first = Settings
    println("main: ${first.level}")
    var seen: Settings? = null
    thread {
        val settings = Settings
        println("worker sets debug")
        settings.level = "debug"
        seen = settings
    }.join()
    println("main: ${Settings.level}")
    println("same instance: ${seen === first}")
}
Output
creating the settings
main: info
worker sets debug
main: debug
same instance: true
  • Verdict: native. An object declaration is a class with exactly one instance. Its initialization is thread-safe and runs on first access.
  • The name Settings is the instance, so code uses it with no accessor call.
  • An object can implement interfaces. Code that takes the interface as a parameter can get a fake in tests, which is the usual way to soften the global access.
  • @Volatile makes the change from the worker thread visible to main.

Consequences

Design Patterns lists these benefits.1 Access to the instance is controlled, because the class owns it. The name space stays clean: the pattern is an improvement over a global variable that any code can overwrite. The class can be subclassed, and the application can choose the subclass. The same mechanism can allow a fixed number of instances greater than one. It is more flexible than a class with only static operations, which cannot be subclassed or replaced.

The costs come from the global access, and from the hand-written lazy creation.

Hidden dependencies. A function that calls Settings.get() inside its body depends on the settings, but its signature does not say so. Hevery shows this with a credit card test that passes in the full suite and throws a NullPointerException when it runs alone. The card used a database, a queue and a processor through singletons, and the suite had set them up in another test. He calls such APIs liars, because they hide what they need, and he concludes that singletons are global state.3

State that leaks between tests. The instance lives as long as the program. A test that changes it changes it for the tests that run after it, so the result depends on the order of the tests:

This code runs but gives a wrong answer on purpose.

class Settings:
    level = "info"  # one shared value, like the field of a singleton


def test_debug_logging():
    Settings.level = "debug"
    return Settings.level == "debug"


def test_default_level():
    return Settings.level == "info"


for name, order in [("first order", [test_default_level, test_debug_logging]),
                    ("second order", [test_debug_logging, test_default_level])]:
    results = [f"{test.__name__} {'pass' if test() else 'FAIL'}" for test in order]
    print(f"{name}: {', '.join(results)}")
Output
first order: test_default_level pass, test_debug_logging pass
second order: test_debug_logging pass, test_default_level FAIL

The fix that Hevery gives is to pass the dependencies to the code that needs them.3 Each test then makes its own object:

class Settings:
    def __init__(self, level="info"):
        self.level = level


def test_debug_logging():
    settings = Settings()
    settings.level = "debug"
    return settings.level == "debug"


def test_default_level():
    settings = Settings()
    return settings.level == "info"


for name, order in [("first order", [test_default_level, test_debug_logging]),
                    ("second order", [test_debug_logging, test_default_level])]:
    results = [f"{test.__name__} {'pass' if test() else 'FAIL'}" for test in order]
    print(f"{name}: {', '.join(results)}")
Output
first order: test_default_level pass, test_debug_logging pass
second order: test_debug_logging pass, test_default_level pass

Lazy creation and threads. The check "is the instance empty?" and the creation are two steps. Two threads can both pass the check before either one stores the instance. The barrier below forces that order, so the program makes two instances every time it runs:

This code runs but gives a wrong answer on purpose.

import threading


class Settings:
    created = 0

    def __init__(self):
        Settings.created += 1


_instance = None
_both_checked = threading.Barrier(2)


def get_settings():
    global _instance
    if _instance is None:
        _both_checked.wait()  # both threads have seen None
        _instance = Settings()
    return _instance


threads = [threading.Thread(target=get_settings) for _ in range(2)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f"instances created: {Settings.created}")
Output
instances created: 2

The fix is to make the check and the creation one step, with a lock:

import threading


class Settings:
    created = 0

    def __init__(self):
        Settings.created += 1


_instance = None
_lock = threading.Lock()


def get_settings():
    global _instance
    with _lock:
        if _instance is None:
            _instance = Settings()
        return _instance


threads = [threading.Thread(target=get_settings) for _ in range(8)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print(f"instances created: {Settings.created}")
Output
instances created: 1

Programs often add a first check before the lock, so that later calls do not take the lock. This is double-checked locking, and it is not safe in every language. In Java, double-checked locking on a plain field is broken: another thread can see the reference before it sees the fields of the object. The Declaration signed by Bacon, Bloch, Pugh and others explains why. It gives two fixes: a volatile field, or a static field in a separate holder class. The class initialization of the JVM makes the second fix safe.911 functools.cache on a function with no arguments is not a strict once in Python either. Its documentation says that the wrapped function can run more than once. This happens if a second thread calls it before the first call has finished.16 The language constructs in the table above avoid all of this.

Python __new__ and __init__. A common Python singleton overrides __new__ to return the stored instance. But when __new__ returns an instance of the class, Python then calls __init__ on it, on every call.15 So each call to Settings() resets the state:

This code runs but gives a wrong answer on purpose.

class Settings:
    _instance = None

    def __new__(cls):
        if cls._instance is None:
            print("creating the settings")
            cls._instance = super().__new__(cls)
        return cls._instance

    def __init__(self):
        self.level = "info"


first = Settings()
first.level = "debug"
second = Settings()
print(first is second, first.level)
Output
creating the settings
True info

There is one instance, as the identity check shows, but the debug level is lost. A module, or a function that returns a stored object, does not have this trap.

Uniqueness can be broken from outside. In Java, a private constructor does not stop reflection: setAccessible(true) lets code call it. Bloch names reflection and serialization as the two ways to get a second instance, and recommends an enum with one constant.10 The Java Language Specification says three things about an enum class. It has no instances other than its constants. Reflective instantiation of enum classes is prohibited. Serialization does not create duplicates.12 The program below makes a second instance of a class singleton, and fails to do so for an enum singleton:

import java.lang.reflect.Constructor;

public class Main {
    static final class ClassSingleton {
        static final ClassSingleton INSTANCE = new ClassSingleton();

        private ClassSingleton() {}
    }

    enum EnumSingleton {
        INSTANCE
    }

    public static void main(String[] args) throws Exception {
        Constructor<ClassSingleton> c = ClassSingleton.class.getDeclaredConstructor();
        c.setAccessible(true);
        ClassSingleton second = c.newInstance();
        System.out.println("class: same instance: " + (second == ClassSingleton.INSTANCE));

        Constructor<EnumSingleton> e =
                EnumSingleton.class.getDeclaredConstructor(String.class, int.class);
        e.setAccessible(true);
        try {
            e.newInstance("SECOND", 1);
        } catch (IllegalArgumentException ex) {
            System.out.println("enum: " + ex.getMessage());
        }
    }
}
Output
class: same instance: false
enum: Cannot reflectively create enum objects

The IllegalArgumentException for an enum class is part of the specification of Constructor.newInstance.29

Order of initialization. Design Patterns warns that C++ does not define the order in which it initializes global objects across translation units. So a singleton held in a global object can be used before it exists.1 The C++ standard still leaves the dynamic initialization of such non-block variables unordered or indeterminately sequenced.27 A function-local static avoids the problem, because it is initialized when control first passes through it.26 The same problem appears between singletons: when the constructor of one singleton calls another, the order of creation is hidden in the code. Hevery's credit card example needed the database before the queue, and the queue before the processor, and nothing in the API showed it.3

Rust makes the global mutable state explicit. A static mut can be read or written only in an unsafe block.25 A safe global with state needs a type such as LazyLock<Mutex<T>>, so the lock is visible at every use. This does not remove the hidden dependency, but it does stop a data race.

When not to use it

The fair summary of the criticism separates the two parts of the intent. Hevery makes this distinction himself. A class with one instance in a program is fine: the application creates it once and passes it to the code that needs it. The problem is the Singleton pattern in the narrow sense, a private constructor with a global static accessor, because it makes global state.4 Global state is transitive: any object that the singleton holds is also global.4 He accepts two cases. A singleton that is immutable, and that holds only immutable objects, has no state to leak. A logger is acceptable in practice, because information flows into it and the program's behaviour does not depend on what it holds.4

Gamma is one of the four authors. In a 2009 interview he said that he was in favour of dropping Singleton from a revised catalog. His reason was that its use is almost always a design smell.2

So do not use the pattern in these cases:

  • To avoid passing an argument. Perhaps the singleton exists because passing the object through three layers is tedious. Then the dependency is real, and the signatures should show it. Kerievsky's Inline Singleton describes the fix. Code needs an object but does not need a global point of access to it. Move the object to a class that stores it and gives access to it, and delete the singleton.5
  • In a program with a dependency injection container. The container can give one instance to every consumer without a global accessor. The .NET documentation says it plainly. If the app requires singleton behaviour, let the service container manage the lifetime, and do not implement the singleton design pattern.6 A service registered with AddSingleton must be thread-safe, because many requests share it.6
  • For state that tests need to control. A test cannot replace a static accessor without extra hooks. If tests need a fake, pass the object in.
  • When "one" is only true today. One database, one window and one user become two databases, a multi-window app and a server with many users. A singleton turns that change into a search through the whole program.

Use it, or a language construct that gives it, when three things are true. The instance is stateless or immutable. It truly belongs to the process. Access goes in one direction, as for a logger or a cache of constant data. Even then, prefer to create it at the top of the program, the place where the objects are wired together, and pass it down. Kerievsky's own refactoring towards the pattern, Limit Instantiation with Singleton, starts from a performance problem. Code creates many instances of an object, and that uses too much memory or slows the system.5 It does not start from a need for global access.

A registry of singletons. Design Patterns discusses how a singleton class can be subclassed: the base class looks up the instance to use in a registry, by name.1 Fowler's service locator is a related idea: one object that knows how to get the services of the application. He notes that his locator is a registry, not a singleton, even though he reaches it through a singleton in his example.7

Dependency injection with a singleton lifetime. The container creates one instance and gives it to every consumer through a constructor. This keeps the "one instance" part of the intent and drops the "global access" part.6

Abstract Factory, Builder and Prototype. Design Patterns notes that these patterns can use Singleton, and that a concrete factory is often a singleton.1 The Factory Method pattern page shows a creator that is passed in instead.

Memoization. A function with no arguments that caches its result is a lazy singleton. Norvig presents Singleton as memoization in dynamic languages.8 Go sync.OnceValue and Python functools.cache both have this shape, with the thread caveat above for functools.cache.1622

Static classes. A class with only static members also has no second instance. Design Patterns notes that it is less flexible, because a static operation cannot be overridden and the class cannot be replaced by a subclass.1 Its state is still global.

Known uses

  • OpenJDK: java.lang.Runtime keeps one instance in a private static final field, returns it from getRuntime, and has a private constructor, in Runtime.java at jdk-25+36.28
  • Design Patterns records the ChangeSet current of Smalltalk-80 and the Session object of InterViews as known uses.1

References

  1. Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 3, Singleton (Intent, Motivation, Consequences, Implementation, Known Uses, Related Patterns)
  2. Larry O'Brien, Design Patterns 15 Years Later, An Interview with Erich Gamma, Richard Helm, and Ralph Johnson, InformIT, October 22, 2009, Gamma's answer on the patterns to drop from a revised catalog (Singleton)
  3. Miško Hevery, Singletons are Pathological Liars, Google Testing Blog, August 17, 2008, the CreditCard test example and the conclusion on global state
  4. Miško Hevery, Root Cause of Singletons, Google Testing Blog, August 2008, the difference between the Singleton pattern and a single instance; global state is transitive; immutable singletons and loggers
  5. Joshua Kerievsky, Refactoring to Patterns, Addison-Wesley, 2004, Chapter 6, Creation, Inline Singleton; Chapter 9, Protection, Limit Instantiation with Singleton (problem and solution of each)
  6. Service lifetimes, .NET dependency injection, Microsoft Learn, Singleton
  7. Martin Fowler, Inversion of Control Containers and the Dependency Injection pattern, January 2004, Using a Service Locator
  8. Peter Norvig, Design Patterns in Dynamic Programming, Object World, May 1996, slide 49 (Singleton as Memoization)
  9. Bacon, Bloch, Bogda and others, The "Double-Checked Locking is Broken" Declaration, the main text; Making it work for static singletons; Fixing Double-Checked Locking using Volatile
  10. Joshua Bloch, Effective Java, third edition, Addison-Wesley, 2018, Item 3, Enforce the singleton property with a private constructor or an enum type; Item 83, Use lazy initialization judiciously
  11. The Java Language Specification, Java SE 25 Edition, 12.4.1 When Initialization Occurs; 12.4.2 Detailed Initialization Procedure
  12. The Java Language Specification, Java SE 25 Edition, 8.9 Enum Classes (no instances other than the enum constants; reflective instantiation prohibited; serialization)
  13. Programming FAQ, Python 3.14 documentation, How do I share global variables across modules?
  14. The Python Language Reference, The import system, Python 3.14, 5.3.1 The module cache
  15. The Python Language Reference, Data model, Python 3.14, object.__new__
  16. The Python Standard Library, functools, Python 3.14, functools.cache and functools.lru_cache (thread safety note)
  17. ECMAScript Language Specification (draft), 16.2.1.10 HostLoadImportedModule (the same result for the same referrer and module request)
  18. Node.js documentation, Modules, CommonJS modules, Caching
  19. Kotlin documentation, Object declarations and expressions, Object declarations (initialization is thread-safe and done on first access)
  20. C# language specification, Classes, 15.12 Static constructors
  21. .NET API reference, System.Lazy<T>, class description and remarks (thread safety modes)
  22. Go standard library, package sync, func OnceValue; type Once
  23. The Go Programming Language Specification, Package initialization; Program initialization
  24. Rust standard library, std::sync::LazyLock, struct description
  25. The Rust Reference, Static items, Mutable statics (rule items.static.mut.safety)
  26. Working Draft, Programming Languages, C++ (N4950), [stmt.dcl] paragraph 3 (block variables with static storage duration, concurrent initialization)
  27. Working Draft, Programming Languages, C++ (N4950), [basic.start.dynamic] (unordered and indeterminately sequenced dynamic initialization of non-block variables)
  28. OpenJDK jdk-25+36 source, java/lang/Runtime.java, currentRuntime, getRuntime and the private constructor, lines 124 to 141
  29. Java SE 25 API, java.lang.reflect.Constructor, newInstance (IllegalArgumentException if the constructor pertains to an enum class)

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.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/NB3KXE/text.yaml