Taskcore
Use a singleton
Also called singleton, single instance, global instance, lazy singleton, shared instance, getInstance, module singleton.
Give a program exactly one IdGenerator that is made on first use, safely across threads, with a module, a static holder, a lazy value or a once cell.
- Evidence
- Code in 9 languages
Task
Give the program exactly one IdGenerator. The generator hands out consecutive ids, 1, 2, 3 and so on, so two parts of the program that get ids from it never get the same id. Every part of the program must get the same instance, the instance must be made on the first use and not before, and two threads that ask for it at the same time must still get one instance.
Then use it. The function singleton_report(calls) gets the instance calls times and takes one id each time. It returns three numbers: the last id minus the first id, how many times the generator was constructed, and how many distinct instances the calls returned. With one instance, the result is always [calls - 1, 1, 1]. For example, singleton_report(3) is [2, 1, 1]. The input calls is from 1 to 1,000,000. The tests also get the instance from 8 threads at the same time and check that all of them get the same object.
The singleton pattern "restricts the instantiation of a class to a singular instance".1 It is one of the Gang of Four patterns, and it is also the pattern that people criticize most: see Pitfalls before you use it.
Solutions
| Language | Where the instance lives | What makes it once | Thread-safe |
|---|---|---|---|
| Python | class attribute _instance |
instance() classmethod with a lock |
yes, double-checked lock |
| JavaScript | a module-level const |
the module is evaluated once | one thread per realm |
| TypeScript | a module-level const |
the module is evaluated once | one thread per realm |
| Java | a static field of a private holder class | class initialization | yes, by the JVM |
| C# | a static Lazy<IdGenerator> |
Lazy<T>.Value |
yes, by default |
| Go | a package variable Instance = sync.OnceValue(...) |
sync.OnceValue |
yes |
| Rust | static INSTANCE: OnceLock<IdGenerator> |
OnceLock::get_or_init |
yes |
| C | a static struct in the .c file |
call_once from <threads.h> |
yes |
| C++ | a static local variable in instance() |
static local initialization | yes, by the language |
- Python uses a class attribute and a lock.
IdGenerator.instance()checks_instance, takes a lock only when it isNone, and checks again under the lock, because another thread can make the instance between the two checks. After the first call, no call takes the lock. A module is the other usual Python singleton: "each module is only imported once per interpreter session",2 and the statements at the top level of a module "are executed only the first time the module name is encountered in an import statement". A module-levelid_generator = IdGenerator()is then one object for the whole program. The solution uses the class form because the test can count constructions and threads. - JavaScript and TypeScript use the module. "ES modules are resolved and cached as URLs",3 so every
importof./id-generator.jsgets the same module and the sameidGeneratorobject. The class is not exported, so other modules cannot callnew IdGenerator(). Plain JavaScript code runs on one thread per realm, so no lock is necessary. A worker thread has its own realm and loads its own copy of the module, so it gets its own instance. - Java uses a holder class. The instance is a
static finalfield of a private nested classHolder. The JVM initializes a class "immediately before the first occurrence" of a use such as a read of a static field,4 soHolderis initialized on the first call ofinstance(), not whenIdGeneratorloads. Class initialization is done under a lock: "For each class or interface C, there is a unique initialization lock LC." So two threads cannot make two instances, andinstance()itself has no lock orvolatilefield. The constructor isprivate, andnextIduses anAtomicLong. - C# uses
Lazy<T>. The reference describesLazy<T>in one line, "Provides support for lazy initialization."5 It runs the factory on the first read ofValue, and the default mode is thread-safe. The class issealedand its constructor isprivate.NextIdusesInterlocked.Increment, becauseLazy<T>protects only the creation: "Lazy initialization is thread-safe, but it doesn't protect the object after creation." - Go uses
sync.OnceValue. "OnceValue returns a function that invokes f only once and returns the value returned by f",6 and the documentation adds: "The returned function may be called concurrently." The package variableInstanceis that function, soidgen.Instance()returns the same pointer each time. The type is exported, but the constructornewIdGeneratoris not. Go code can still writeidgen.IdGenerator{}, so the singleton is a convention that the package documents, not a rule that the compiler enforces. - Rust uses a
static OnceLock. The documentation ofOnceLockstarts: "A synchronization primitive which can nominally be written to only once."7INSTANCE.get_or_init(IdGenerator::new)runsnewon the first call and returns a&'static IdGeneratorafter that. Astaticmust beSync, so the counter is anAtomicU64; a plainu64field thatnext_idchanges would not compile. - C uses
call_once. The struct is defined only inid_generator.c, so other files can hold astruct id_generator *but cannot declare one.call_once(&instance_once, make_instance)runsmake_instanceonce, even when several threads call it. The counter is anatomic_long. - C++ uses a static local variable.
static IdGenerator g;insideinstance()is made on the first call. The language makes this safe: "If multiple threads attempt to initialize the same static local variable concurrently, the initialization occurs exactly once".8 This form is often called the Meyers singleton. The copy constructor and copy assignment are deleted, so code cannot copy the instance.
Alternatives
- A language construct. Kotlin has the singleton in the language: "objects allow you to define a class and create an instance of it in a single step",9 and the documentation adds: "The initialization of an object declaration is thread-safe and done on first access."
object IdGenerator { ... }replaces all of the code above. - Make it eagerly. If the instance is cheap to make and the program always uses it, make it at startup: a Java
static finalfield inIdGeneratoritself, a Go package variablevar instance = &IdGenerator{}, or a C#static readonlyfield. The language still makes it once, and the code has no lazy step. - Pass the instance instead. Make one
IdGeneratorinmainand pass it to the code that needs it, as a constructor parameter or a function parameter. The program still has one instance, but a test can pass its own instance. This is dependency injection, and it removes most of the pitfalls below.
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
single-call: one call makes the instance and takes id 1, so the result is[0, 1, 1].pair: the second call must return the instance of the first call, not make another one. A missing check ininstance()shows here.limit: 1,000,000 calls. After the first call,instance()must not take a lock or make an object, or this case is slow. The ids fit in 32 bits, but the solutions use 64-bit counters, because a real program can run for a long time.- The tests call
singleton_reportmore than once in one process, so the second call starts at a higher id. The report uses the difference of the ids, so the result does not change. - The thread test gets the instance from 8 threads at the same time, and then checks that the generator was constructed once.
Pitfalls
- Global state. "Some consider the singleton to be an anti-pattern that introduces global state into an application, often unnecessarily."1 Any code can get the instance, so a function that uses it does not show this in its parameters, and two functions that look independent can affect each other through it. "This increased coupling can introduce difficulties with unit testing."
- State that leaks from one test to the next. A singleton lives as long as the process, and a test runner runs many tests in one process. A change that one test makes is still there in the next test. Code then adds a reset that only tests call:
class Config:
_instance = None
@classmethod
def instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
self.values = {}
def test_turns_on_debug():
Config.instance().values["debug"] = True
def test_default_is_off():
return Config.instance().values.get("debug", False) is False
test_turns_on_debug()
print(test_default_is_off()) # fails: the state of the first test is still there
Config._instance = None # a reset that only tests call
print(test_default_is_off())
False
True
The reset is in production code but is not part of its real interface, and a test that forgets to call it gives a result that depends on the order of the tests. Passing the instance as a parameter avoids the problem.
- Python
__new__without a guard in__init__. A common Python singleton overrides__new__to return the stored instance. But each call ofSettings()still calls__init__on the instance that__new__returns, so__init__resets the state:
class Settings:
_instance = None
def __new__(cls):
if cls._instance is None:
cls._instance = super().__new__(cls)
return cls._instance
def __init__(self):
self.values = {} # runs again on every call of Settings()
a = Settings()
a.values["debug"] = True
b = Settings()
print(a is b, a.values)
True {}
Use a classmethod such as instance(), a module, or a guard in __init__.
- Double-checked locking without a memory barrier. In Java and C++, a field that is checked outside the lock must be
volatileor atomic. Without it, another thread can see the reference before it sees the fields that the constructor set. The holder class,Lazy<T>,sync.OnceValue,OnceLock,call_onceand the C++ static local do this correctly, so use them instead of a hand-written check. - A singleton per class loader, process or worker. "One instance" means one per Java class loader, one per JavaScript realm and one per process. Two web application class loaders, two worker threads or two server processes each have their own instance, so a singleton cannot hand out unique ids across processes. Use a database sequence or a UUID for that.
- The instance does not make its methods thread-safe. The once step protects only the creation.
next_idneeds its own lock or atomic counter in each solution.
Related tasks
- Define a class defines a class whose instances each have their own state.
- Static members explains the static fields and class methods that hold the instance.
- Classes and instances explains how a class makes instances.
- Singleton pattern explains the design pattern and when to use it.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-singleton/.
import threading
class IdGenerator:
"""Hands out consecutive ids. Get the one instance with IdGenerator.instance()."""
_instance = None
_lock = threading.Lock()
constructions = 0 # how many times __init__ has run
def __init__(self):
IdGenerator.constructions += 1
self._next = 1
self._ids_lock = threading.Lock()
@classmethod
def instance(cls):
if cls._instance is None: # fast path, no lock after the first call
with cls._lock:
if cls._instance is None: # another thread may have made it
cls._instance = cls()
return cls._instance
def next_id(self):
with self._ids_lock:
n = self._next
self._next += 1
return n
def singleton_report(calls):
seen = []
ids = []
for _ in range(calls):
g = IdGenerator.instance()
if not any(g is s for s in seen):
seen.append(g)
ids.append(g.next_id())
return [ids[-1] - ids[0], IdGenerator.constructions, len(seen)]
test_id_generator.py 33 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-a-singleton/.
import threading
import pytest
from id_generator import IdGenerator, singleton_report
CASES = {
"three-calls": (3, [2, 1, 1]),
"ten-calls": (10, [9, 1, 1]),
"single-call": (1, [0, 1, 1]),
"pair": (2, [1, 1, 1]),
"limit": (1000000, [999999, 1, 1]),
}
@pytest.mark.parametrize("name", CASES)
def test_singleton_report(name):
calls, want = CASES[name]
assert singleton_report(calls) == want
def test_threads_share_one_instance():
got = []
threads = [threading.Thread(target=lambda: got.append(IdGenerator.instance())) for _ in range(8)]
for t in threads:
t.start()
for t in threads:
t.join()
assert all(g is got[0] for g in got)
assert IdGenerator.constructions == 1
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
#include "id_generator.hpp"
#include <algorithm>
namespace {
std::atomic<int> construction_count{0};
}
IdGenerator::IdGenerator() {
construction_count++;
}
IdGenerator &IdGenerator::instance() {
// A local static is made on the first call, and the language makes this
// thread-safe: other threads wait until the initialization is done.
static IdGenerator g;
return g;
}
int IdGenerator::constructions() {
return construction_count.load();
}
std::vector<long> singleton_report(int calls) {
std::vector<const IdGenerator *> seen;
long first = 0;
long last = 0;
for (int i = 0; i < calls; i++) {
IdGenerator &g = IdGenerator::instance();
if (std::find(seen.begin(), seen.end(), &g) == seen.end()) {
seen.push_back(&g);
}
last = g.next_id();
if (i == 0) {
first = last;
}
}
return {last - first, IdGenerator::constructions(), static_cast<long>(seen.size())};
}
id_generator.hpp 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
#ifndef ID_GENERATOR_HPP
#define ID_GENERATOR_HPP
#include <atomic>
#include <vector>
// Hands out consecutive ids. Get the one instance with IdGenerator::instance().
class IdGenerator {
public:
static IdGenerator &instance();
static int constructions();
IdGenerator(const IdGenerator &) = delete; // no copies
IdGenerator &operator=(const IdGenerator &) = delete;
long next_id() { return next_++; }
private:
IdGenerator(); // private: only instance() can make one
std::atomic<long> next_{1};
};
std::vector<long> singleton_report(int calls);
#endif
test_id_generator.cpp 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
#include "id_generator.hpp"
#include <iostream>
#include <string_view>
#include <thread>
#include <vector>
static int failures = 0;
static void check(std::string_view name, int calls, const std::vector<long> &want) {
if (singleton_report(calls) != want) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
std::vector<IdGenerator *> got(8);
{
std::vector<std::jthread> threads;
for (auto &p : got) {
threads.emplace_back([&p] { p = &IdGenerator::instance(); });
}
}
for (auto *p : got) {
if (p != &IdGenerator::instance()) {
std::cerr << "case threads failed\n";
failures++;
}
}
check("three-calls", 3, {2, 1, 1});
check("ten-calls", 10, {9, 1, 1});
check("single-call", 1, {0, 1, 1});
check("pair", 2, {1, 1, 1});
check("limit", 1000000, {999999, 1, 1});
if (failures > 0) {
return 1;
}
std::cout << "all cases pass\n";
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
/** Hands out consecutive ids. Get the one instance with {@code IdGenerator.instance()}. */
public final class IdGenerator {
static final AtomicInteger CONSTRUCTIONS = new AtomicInteger();
private final AtomicLong next = new AtomicLong(1);
private IdGenerator() { // private: no other class can make one
CONSTRUCTIONS.incrementAndGet();
}
// The holder class is initialized on the first call of instance(), and the
// JVM runs class initialization once, under a lock.
private static final class Holder {
static final IdGenerator INSTANCE = new IdGenerator();
}
public static IdGenerator instance() {
return Holder.INSTANCE;
}
public long nextId() {
return next.getAndIncrement();
}
public static List<Long> singletonReport(int calls) {
List<IdGenerator> seen = new ArrayList<>();
long first = 0;
long last = 0;
for (int i = 0; i < calls; i++) {
IdGenerator g = instance();
if (seen.stream().noneMatch(s -> s == g)) {
seen.add(g);
}
last = g.nextId();
if (i == 0) {
first = last;
}
}
return List.of(last - first, (long) CONSTRUCTIONS.get(), (long) seen.size());
}
}
IdGeneratorTest.java 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class IdGeneratorTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("three-calls", 3, List.of(2L, 1L, 1L)),
Arguments.of("ten-calls", 10, List.of(9L, 1L, 1L)),
Arguments.of("single-call", 1, List.of(0L, 1L, 1L)),
Arguments.of("pair", 2, List.of(1L, 1L, 1L)),
Arguments.of("limit", 1000000, List.of(999999L, 1L, 1L)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void singletonReport(String name, int calls, List<Long> want) {
assertEquals(want, IdGenerator.singletonReport(calls));
}
@Test
void threadsShareOneInstance() throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(8);
try {
Callable<IdGenerator> task = IdGenerator::instance;
List<Future<IdGenerator>> got = pool.invokeAll(Collections.nCopies(8, task));
for (Future<IdGenerator> f : got) {
assertSame(IdGenerator.instance(), f.get());
}
} finally {
pool.shutdown();
}
assertEquals(1, IdGenerator.CONSTRUCTIONS.get());
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
#include "id_generator.h"
#include <stdatomic.h>
#include <threads.h>
struct id_generator {
atomic_long next;
};
static struct id_generator instance;
static once_flag instance_once = ONCE_FLAG_INIT;
static int constructions = 0;
static void make_instance(void) {
atomic_init(&instance.next, 1);
constructions++;
}
struct id_generator *id_generator_instance(void) {
call_once(&instance_once, make_instance); // runs make_instance once
return &instance;
}
long id_generator_next(struct id_generator *g) {
return atomic_fetch_add(&g->next, 1); // safe when threads share g
}
int id_generator_constructions(void) {
return constructions;
}
void singleton_report(int calls, long out[3]) {
struct id_generator *first_g = NULL;
long distinct = 0;
long first = 0;
long last = 0;
for (int i = 0; i < calls; i++) {
struct id_generator *g = id_generator_instance();
if (g != first_g) { // counts each change of the pointer
distinct++;
first_g = g;
}
last = id_generator_next(g);
if (i == 0) {
first = last;
}
}
out[0] = last - first;
out[1] = constructions;
out[2] = distinct;
}
id_generator.h 19 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
#ifndef ID_GENERATOR_H
#define ID_GENERATOR_H
// The one id generator of the program. Its struct is defined in the .c file,
// so other files can hold a pointer to it but cannot make another one.
struct id_generator;
struct id_generator *id_generator_instance(void);
long id_generator_next(struct id_generator *g);
int id_generator_constructions(void);
// singleton_report gets the instance calls times, takes one id each time, and
// writes [last id - first id, constructions, distinct instances] to out.
void singleton_report(int calls, long out[3]);
#endif
test_id_generator.c 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
#include "id_generator.h"
#include <stdio.h>
#include <string.h>
static int failures = 0;
static void check(const char *name, int calls, long a, long b, long c) {
const long want[3] = {a, b, c};
long got[3];
singleton_report(calls, got);
if (memcmp(got, want, sizeof want) != 0) {
fprintf(stderr, "case %s failed\n", name);
failures++;
}
}
int main(void) {
check("three-calls", 3, 2, 1, 1);
check("ten-calls", 10, 9, 1, 1);
check("single-call", 1, 0, 1, 1);
check("pair", 2, 1, 1, 1);
check("limit", 1000000, 999999, 1, 1);
if (id_generator_instance() != id_generator_instance() || id_generator_constructions() != 1) {
fprintf(stderr, "case one-instance failed\n");
failures++;
}
if (failures > 0) {
return 1;
}
printf("all cases pass\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
using System;
using System.Collections.Generic;
using System.Threading;
/// <summary>Hands out consecutive ids. Get the one instance with IdGenerator.Instance.</summary>
public sealed class IdGenerator
{
// Lazy<T> runs the factory once, on the first read of Value, and is
// thread-safe by default.
private static readonly Lazy<IdGenerator> lazy = new(() => new IdGenerator());
private static int constructions;
private long next;
private IdGenerator() // private: no other class can make one
{
Interlocked.Increment(ref constructions);
}
public static IdGenerator Instance => lazy.Value;
public static int Constructions => Volatile.Read(ref constructions);
public long NextId() => Interlocked.Increment(ref next);
public static long[] Report(int calls)
{
var seen = new List<IdGenerator>();
long first = 0, last = 0;
for (var i = 0; i < calls; i++)
{
var g = Instance;
if (!seen.Exists(s => ReferenceEquals(s, g)))
{
seen.Add(g);
}
last = g.NextId();
if (i == 0)
{
first = last;
}
}
return [last - first, Constructions, seen.Count];
}
}
IdGeneratorTests.cs 34 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
using System.Linq;
using System.Threading.Tasks;
using Xunit;
public sealed class IdGeneratorTests
{
public static TheoryData<string, int, long[]> Cases => new()
{
{ "three-calls", 3, new long[] { 2, 1, 1 } },
{ "ten-calls", 10, new long[] { 9, 1, 1 } },
{ "single-call", 1, new long[] { 0, 1, 1 } },
{ "pair", 2, new long[] { 1, 1, 1 } },
{ "limit", 1000000, new long[] { 999999, 1, 1 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void Report(string name, int calls, long[] want)
{
Assert.NotNull(name);
Assert.Equal(want, IdGenerator.Report(calls));
}
[Fact]
public async Task ThreadsShareOneInstance()
{
var got = await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(() => IdGenerator.Instance)));
Assert.All(got, g => Assert.Same(IdGenerator.Instance, g));
Assert.Equal(1, IdGenerator.Constructions);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
// A module is evaluated once, and every import gets the same bindings, so a
// module-level object is a singleton. The class is not exported, so other
// code cannot make a second instance.
let constructions = 0;
class IdGenerator {
#next = 1;
constructor() {
constructions++;
}
nextId() {
return this.#next++;
}
}
export const idGenerator = new IdGenerator();
export function constructionCount() {
return constructions;
}
export function singletonReport(calls) {
const seen = new Set();
const ids = [];
for (let i = 0; i < calls; i++) {
const g = idGenerator;
seen.add(g);
ids.push(g.nextId());
}
return [ids[ids.length - 1] - ids[0], constructions, seen.size];
}
id-generator.test.js 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { constructionCount, idGenerator, singletonReport } from "./id-generator.js";
import * as again from "./id-generator.js";
const cases = [
["three-calls", 3, [2, 1, 1]],
["ten-calls", 10, [9, 1, 1]],
["single-call", 1, [0, 1, 1]],
["pair", 2, [1, 1, 1]],
["limit", 1000000, [999999, 1, 1]],
];
for (const [name, calls, want] of cases) {
test(name, () => {
assert.deepEqual(singletonReport(calls), want);
});
}
test("a second import gets the same instance", () => {
assert.equal(again.idGenerator, idGenerator);
assert.equal(constructionCount(), 1);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
// A module is evaluated once, and every import gets the same bindings, so a
// module-level object is a singleton. The class is not exported, so other
// code cannot make a second instance.
let constructions = 0;
class IdGenerator {
#next = 1;
constructor() {
constructions++;
}
nextId(): number {
return this.#next++;
}
}
export const idGenerator: IdGenerator = new IdGenerator();
export function constructionCount(): number {
return constructions;
}
export function singletonReport(calls: number): number[] {
const seen = new Set<IdGenerator>();
const ids: number[] = [];
for (let i = 0; i < calls; i++) {
const g = idGenerator;
seen.add(g);
ids.push(g.nextId());
}
return [ids[ids.length - 1] - ids[0], constructions, seen.size];
}
id-generator.test.ts 27 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { constructionCount, idGenerator, singletonReport } from "./id-generator.ts";
import * as again from "./id-generator.ts";
const cases: [string, number, number[]][] = [
["three-calls", 3, [2, 1, 1]],
["ten-calls", 10, [9, 1, 1]],
["single-call", 1, [0, 1, 1]],
["pair", 2, [1, 1, 1]],
["limit", 1000000, [999999, 1, 1]],
];
for (const [name, calls, want] of cases) {
test(name, () => {
assert.deepEqual(singletonReport(calls), want);
});
}
test("a second import gets the same instance", () => {
assert.equal(again.idGenerator, idGenerator);
assert.equal(constructionCount(), 1);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
// Package idgen has one IdGenerator for the whole program. sync.OnceValue
// makes it on the first call and returns the same pointer after that.
package idgen
import (
"sync"
"sync/atomic"
)
// IdGenerator hands out consecutive ids.
type IdGenerator struct {
next atomic.Int64
}
var constructions atomic.Int64
func newIdGenerator() *IdGenerator {
constructions.Add(1)
return &IdGenerator{}
}
// Instance returns the one IdGenerator.
var Instance = sync.OnceValue(newIdGenerator)
// NextID returns the next id, starting at 1. It is safe for concurrent use.
func (g *IdGenerator) NextID() int64 {
return g.next.Add(1)
}
// Constructions returns how many times the generator has been made.
func Constructions() int64 {
return constructions.Load()
}
// Report gets the instance calls times and takes one id each time.
func Report(calls int) []int64 {
seen := map[*IdGenerator]bool{}
var first, last int64
for i := 0; i < calls; i++ {
g := Instance()
seen[g] = true
last = g.NextID()
if i == 0 {
first = last
}
}
return []int64{last - first, Constructions(), int64(len(seen))}
}
idgen_test.go 51 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
package idgen
import (
"slices"
"sync"
"testing"
)
var cases = []struct {
name string
calls int
want []int64
}{
{"three-calls", 3, []int64{2, 1, 1}},
{"ten-calls", 10, []int64{9, 1, 1}},
{"single-call", 1, []int64{0, 1, 1}},
{"pair", 2, []int64{1, 1, 1}},
{"limit", 1000000, []int64{999999, 1, 1}},
}
func TestReport(t *testing.T) {
for _, c := range cases {
if got := Report(c.calls); !slices.Equal(got, c.want) {
t.Errorf("%s: got %v, want %v", c.name, got, c.want)
}
}
}
func TestGoroutinesShareOneInstance(t *testing.T) {
var wg sync.WaitGroup
got := make([]*IdGenerator, 8)
for i := range got {
wg.Add(1)
go func(i int) {
defer wg.Done()
got[i] = Instance()
}(i)
}
wg.Wait()
for _, g := range got {
if g != Instance() {
t.Fatal("two instances")
}
}
if Constructions() != 1 {
t.Errorf("constructions = %d", Constructions())
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::OnceLock;
/// Hands out consecutive ids. Get the one instance with `IdGenerator::instance()`.
pub struct IdGenerator {
next: AtomicU64,
}
static INSTANCE: OnceLock<IdGenerator> = OnceLock::new();
static CONSTRUCTIONS: AtomicU64 = AtomicU64::new(0);
impl IdGenerator {
fn new() -> Self {
CONSTRUCTIONS.fetch_add(1, Ordering::SeqCst);
IdGenerator { next: AtomicU64::new(1) }
}
/// Returns the one instance. `OnceLock` runs `new` once, even when
/// several threads call this at the same time.
pub fn instance() -> &'static IdGenerator {
INSTANCE.get_or_init(IdGenerator::new)
}
pub fn next_id(&self) -> u64 {
self.next.fetch_add(1, Ordering::Relaxed)
}
pub fn constructions() -> u64 {
CONSTRUCTIONS.load(Ordering::SeqCst)
}
}
pub fn singleton_report(calls: u32) -> Vec<u64> {
let mut seen: Vec<*const IdGenerator> = Vec::new();
let (mut first, mut last) = (0, 0);
for i in 0..calls {
let g = IdGenerator::instance();
if !seen.contains(&(g as *const IdGenerator)) {
seen.push(g);
}
last = g.next_id();
if i == 0 {
first = last;
}
}
vec![last - first, IdGenerator::constructions(), seen.len() as u64]
}
tests/id_generator_test.rs 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-a-singleton/.
use algo_use_a_singleton::{singleton_report, IdGenerator};
use std::thread;
#[test]
fn cases() {
let cases: Vec<(&str, u32, Vec<u64>)> = vec![
("three-calls", 3, vec![2, 1, 1]),
("ten-calls", 10, vec![9, 1, 1]),
("single-call", 1, vec![0, 1, 1]),
("pair", 2, vec![1, 1, 1]),
("limit", 1000000, vec![999999, 1, 1]),
];
for (name, calls, want) in cases {
assert_eq!(singleton_report(calls), want, "{name}");
}
}
#[test]
fn threads_share_one_instance() {
let handles: Vec<_> = (0..8)
.map(|_| thread::spawn(|| IdGenerator::instance() as *const IdGenerator as usize))
.collect();
let first = IdGenerator::instance() as *const IdGenerator as usize;
for h in handles {
assert_eq!(h.join().unwrap(), first);
}
assert_eq!(IdGenerator::constructions(), 1);
}
References
- Singleton pattern, Wikipedia, Introduction; Criticism
- 6. Modules, The Python Tutorial, 6.1 More on Modules
- Modules, ECMAScript modules, Node.js documentation, URLs
- Chapter 12, Execution, The Java Language Specification, Java SE 25 Edition, 12.4.1 When Initialization Occurs; 12.4.2 Detailed Initialization Procedure
- Lazy<T> Class, .NET API reference, Definition; Examples
- sync package, Go standard library, func OnceValue
- OnceLock in std::sync, The Rust Standard Library, Description
- Storage duration, cppreference.com, Static local variables
- Object declarations and expressions, Kotlin documentation, Object declarations
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 |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag 1X7NQW Edit this page History Report an error Markdown