{"id":"6b08bd3d80884893657cca05","slug":"singleton","title":"Singleton – one instance, and the reasons to hand it to a DI container","summary":"Singleton guarantees that a class has exactly one instance available to the whole application. We show thread-safe implementations in five languages and explain why today it is usually better to register the object as a singleton in a DI container.","servedLang":"en","availableLangs":["pl","en"],"topics":["singleton","abstract-factory","facade","solid"],"techs":["dotnet","typescript","java","go","python"],"tags":["gof","creational","singleton","dependency-injection","thread-safety"],"level":"beginner","kind":"article","access":"members","status":"published","cover":null,"author":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","community":false},"readingMinutes":10,"stats":{"views":4,"likes":0,"bookmarks":0,"comments":0},"publishedAt":"2026-11-26T23:14:05.420Z","updatedAt":"2026-11-27T13:04:46.165Z","requestedLang":"en","theme":{"hero":"minimal","heroMedia":null,"accent":"green","background":"grid","weaveResources":true,"toc":"right"},"seoDescription":"The Singleton design pattern – the multiple-instances problem, thread-safe implementations (Lazy<T>, enum, sync.OnceValue, Python modules), the downsides of global state, Singleton vs dependency injection, examples from .NET, Java, Go and Python.","wordCount":1846,"doc":{"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Singleton","marks":[{"type":"bold"}]},{"type":"text","text":" is the best-known and at the same time the most criticised pattern in the GoF catalog. It promises two things: a class has "},{"type":"text","text":"exactly one instance","marks":[{"type":"bold"}]},{"type":"text","text":", and there is a "},{"type":"text","text":"global point of access","marks":[{"type":"bold"}]},{"type":"text","text":" to it. The first is sometimes genuinely needed. The second – far less often than it seems."}]},{"type":"callout","attrs":{"variant":"info","title":"In short"},"content":[{"type":"bulletList","content":[{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"A private constructor plus a static access point guarantee one instance per process."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"The implementation must be thread-safe – every language has a ready, proven mechanism for that."}]}]},{"type":"listItem","content":[{"type":"paragraph","content":[{"type":"text","text":"Global access makes testing hard and hides dependencies; a "},{"type":"text","text":"singleton","marks":[{"type":"italic"}]},{"type":"text","text":" lifetime in a DI container is usually better."}]}]}]}]},{"type":"stats","attrs":{"items":[{"value":"1","label":"instance per process","hint":"not per server or per cluster"},{"value":"2","label":"promises of the pattern","hint":"one instance and global access"},{"value":"0","label":"hidden dependencies","hint":"what we want after switching to DI"}]}},{"type":"heading","attrs":{"level":2,"id":"the-problem-counters-that-count-to-half"},"content":[{"type":"text","text":"The problem: counters that count to half"}]},{"type":"paragraph","content":[{"type":"text","text":"A shop collects metrics – the number of placed orders, failed payments, cache hits. The counter registry is a simple class with a map of names to values. The problem appeared after a few sprints: the dashboard chart showed half as many orders as there were in the database."}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"orders.ts / payments.ts"},"content":[{"type":"text","text":"// orders.ts\nconst metrics = new MetricsRegistry();\nmetrics.increment(\"orders_placed\");\n\n// payments.ts – another module, another registry\nconst metrics = new MetricsRegistry();\nmetrics.increment(\"orders_placed\"); // counted in a different map"}]},{"type":"paragraph","content":[{"type":"text","text":"Each module created its own registry, and the metrics exporter read only one of them. We need a guarantee that one registry exists in the process, and a convenient way for all code to reach exactly that one."}]},{"type":"heading","attrs":{"level":2,"id":"the-solution-a-private-constructor-and-one-access-point"},"content":[{"type":"text","text":"The solution: a private constructor and one access point"}]},{"type":"paragraph","content":[{"type":"text","text":"The classic Singleton closes the constructor (nobody outside can call "},{"type":"text","text":"new","marks":[{"type":"code"}]},{"type":"text","text":") and exposes a static property or method that creates the instance on the first call and returns the same one on subsequent calls."}]},{"type":"diagram","attrs":{"kind":"mermaid","code":"classDiagram\n  class MetricsRegistry {\n    -instance$ MetricsRegistry\n    -counters Map\n    -MetricsRegistry()\n    +getInstance()$ MetricsRegistry\n    +increment(name)\n    +get(name) long\n  }\n  MetricsRegistry --> MetricsRegistry : instance\n  OrdersModule ..> MetricsRegistry : getInstance()\n  PaymentsModule ..> MetricsRegistry : getInstance()","caption":"Structure of the classic Singleton"}},{"type":"table","content":[{"type":"tableRow","content":[{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Element"}]}]},{"type":"tableHeader","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"Purpose"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"private constructor"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"blocks creating more instances with "},{"type":"text","text":"new","marks":[{"type":"code"}]}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"static field holding the instance"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"stores the only object"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"static access point"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"returns the instance, creating it lazily on first use"}]}]}]},{"type":"tableRow","content":[{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"thread safety"}]}]},{"type":"tableCell","attrs":{"colspan":1,"rowspan":1},"content":[{"type":"paragraph","content":[{"type":"text","text":"two threads at once cannot create two instances"}]}]}]}]},{"type":"heading","attrs":{"level":2,"id":"implementation-in-five-languages"},"content":[{"type":"text","text":"Implementation in five languages"}]},{"type":"paragraph","content":[{"type":"text","text":"The most common Singleton bug is a hand-written \"check for null and create\" without synchronisation – two threads may then see "},{"type":"text","text":"null","marks":[{"type":"code"}]},{"type":"text","text":" at the same time. Every language has a ready tool for this: "},{"type":"text","text":"Lazy<T>","marks":[{"type":"code"}]},{"type":"text","text":" in .NET, the "},{"type":"text","text":"enum","marks":[{"type":"code"}]},{"type":"text","text":" type in Java, "},{"type":"text","text":"sync.OnceValue","marks":[{"type":"code"}]},{"type":"text","text":" in Go, and in Python and TypeScript – the module system itself."}]},{"type":"codeGroup","attrs":{"title":"MetricsRegistry"},"content":[{"type":"codeBlock","attrs":{"language":"csharp","filename":"MetricsRegistry.cs"},"content":[{"type":"text","text":"using System.Collections.Concurrent;\n\nParallel.For(0, 1000, _ => MetricsRegistry.Instance.Increment(\"hits\"));\nConsole.WriteLine(MetricsRegistry.Instance.Get(\"hits\")); // 1000\n\npublic sealed class MetricsRegistry\n{\n    // Lazy<T> is thread-safe by default (LazyThreadSafetyMode.ExecutionAndPublication).\n    private static readonly Lazy<MetricsRegistry> LazyInstance = new(() => new MetricsRegistry());\n\n    private readonly ConcurrentDictionary<string, long> _counters = new();\n\n    private MetricsRegistry() => Console.WriteLine(\"Registry created once\");\n\n    public static MetricsRegistry Instance => LazyInstance.Value;\n\n    public void Increment(string name) => _counters.AddOrUpdate(name, 1, (_, value) => value + 1);\n\n    public long Get(string name) => _counters.GetValueOrDefault(name);\n}"}]},{"type":"codeBlock","attrs":{"language":"typescript","filename":"metrics-registry.ts"},"content":[{"type":"text","text":"class MetricsRegistry {\n  private static instance?: MetricsRegistry;\n  private readonly counters = new Map<string, number>();\n\n  private constructor() {\n    console.log(\"Registry created once\");\n  }\n\n  static getInstance(): MetricsRegistry {\n    // JavaScript runs your code on a single thread, so no locking is needed.\n    return (MetricsRegistry.instance ??= new MetricsRegistry());\n  }\n\n  increment(name: string): void {\n    this.counters.set(name, (this.counters.get(name) ?? 0) + 1);\n  }\n\n  get(name: string): number {\n    return this.counters.get(name) ?? 0;\n  }\n}\n\n// Idiomatic alternative: a module is evaluated once, so its exports are shared.\nexport const metrics = MetricsRegistry.getInstance();\n\nmetrics.increment(\"hits\");\nMetricsRegistry.getInstance().increment(\"hits\");\nconsole.log(metrics.get(\"hits\")); // 2"}]},{"type":"codeBlock","attrs":{"language":"java","filename":"Metrics.java"},"content":[{"type":"text","text":"import java.util.concurrent.ConcurrentHashMap;\nimport java.util.concurrent.atomic.LongAdder;\nimport java.util.stream.IntStream;\n\n// An enum is the singleton recommended in Effective Java:\n// thread-safe, and immune to serialization and reflection attacks.\nenum MetricsRegistry {\n    INSTANCE;\n\n    private final ConcurrentHashMap<String, LongAdder> counters = new ConcurrentHashMap<>();\n\n    public void increment(String name) {\n        counters.computeIfAbsent(name, k -> new LongAdder()).increment();\n    }\n\n    public long get(String name) {\n        LongAdder adder = counters.get(name);\n        return adder == null ? 0 : adder.sum();\n    }\n}\n\npublic class Metrics {\n    public static void main(String[] args) {\n        IntStream.range(0, 1_000).parallel().forEach(i -> MetricsRegistry.INSTANCE.increment(\"hits\"));\n        System.out.println(MetricsRegistry.INSTANCE.get(\"hits\")); // 1000\n    }\n}"}]},{"type":"codeBlock","attrs":{"language":"go","filename":"metrics.go"},"content":[{"type":"text","text":"package main\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n)\n\ntype MetricsRegistry struct {\n\tmu       sync.Mutex\n\tcounters map[string]int64\n}\n\n// Default returns the process-wide registry. sync.OnceValue (Go 1.21+) runs the\n// constructor exactly once, even when many goroutines call it at the same time.\nvar Default = sync.OnceValue(func() *MetricsRegistry {\n\tfmt.Println(\"registry created once\")\n\treturn &MetricsRegistry{counters: make(map[string]int64)}\n})\n\nfunc (r *MetricsRegistry) Inc(name string) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tr.counters[name]++\n}\n\nfunc (r *MetricsRegistry) Get(name string) int64 {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\treturn r.counters[name]\n}\n\nfunc main() {\n\tvar wg sync.WaitGroup\n\tfor i := 0; i < 1000; i++ {\n\t\twg.Add(1)\n\t\tgo func() {\n\t\t\tdefer wg.Done()\n\t\t\tDefault().Inc(\"hits\")\n\t\t}()\n\t}\n\twg.Wait()\n\tfmt.Println(Default().Get(\"hits\")) // 1000\n}"}]},{"type":"codeBlock","attrs":{"language":"python","filename":"metrics.py"},"content":[{"type":"text","text":"import threading\nfrom collections import Counter\nfrom concurrent.futures import ThreadPoolExecutor\n\n\nclass MetricsRegistry:\n    def __init__(self) -> None:\n        print(\"registry created once\")\n        self._lock = threading.Lock()\n        self._counters: Counter[str] = Counter()\n\n    def inc(self, name: str) -> None:\n        with self._lock:\n            self._counters[name] += 1\n\n    def get(self, name: str) -> int:\n        with self._lock:\n            return self._counters[name]\n\n\n# The Pythonic singleton: a module is executed once per process (imports are cached\n# in sys.modules), so every `from metrics import registry` gets the same object.\nregistry = MetricsRegistry()\n\n\nif __name__ == \"__main__\":\n    with ThreadPoolExecutor(max_workers=8) as pool:\n        for _ in range(1000):\n            pool.submit(registry.inc, \"hits\")\n    print(registry.get(\"hits\"))  # 1000"}]}]}]},"toc":[{"id":"the-problem-counters-that-count-to-half","text":"The problem: counters that count to half","level":2,"locked":false},{"id":"the-solution-a-private-constructor-and-one-access-point","text":"The solution: a private constructor and one access point","level":2,"locked":false},{"id":"implementation-in-five-languages","text":"Implementation in five languages","level":2,"locked":false},{"id":"singleton-vs-dependency-injection","text":"Singleton vs dependency injection","level":2,"locked":true},{"id":"step-by-step-from-singleton-to-a-container","text":"Step by step: from Singleton to a container","level":2,"locked":true},{"id":"when-to-use-it-and-when-not-to","text":"When to use it and when not to","level":2,"locked":true},{"id":"related-patterns","text":"Related patterns","level":2,"locked":true},{"id":"in-practice","text":"In practice","level":2,"locked":true},{"id":"quick-check","text":"Quick check","level":2,"locked":true},{"id":"summary","text":"Summary","level":2,"locked":true}],"locked":true,"paywall":null,"previewRatio":0.3,"totalBlocks":39,"visibleBlocks":14,"resources":[{"id":"6b0857a53c96f2d34d0b321f","type":"video","provider":"youtube","url":"https://www.youtube.com/watch?v=hUE_j6q0LTQ","embedUrl":"https://www.youtube-nocookie.com/embed/hUE_j6q0LTQ","title":"Singleton Pattern – Design Patterns (ep 6)","description":"","author":"Christopher Okhravi","thumbnailUrl":"https://i.ytimg.com/vi/hUE_j6q0LTQ/hqdefault.jpg","durationSec":null,"lang":"en","topics":["singleton"],"techs":["general"],"tags":[],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"seed","publishedAt":null,"popularity":0,"verifiedAt":"2026-11-26T00:00:00.000Z","curated":true,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:37.809Z","updatedAt":"2026-11-26T16:00:37.809Z"},{"id":"6b0857bf3c96f2d34d0b4289","type":"article","provider":"web","url":"https://gameprogrammingpatterns.com/singleton.html","embedUrl":null,"title":"Singleton · Design Patterns Revisited · Game Programming Patterns","description":"","author":"Robert Nystrom","thumbnailUrl":null,"durationSec":null,"lang":"en","topics":["singleton"],"techs":["general"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":65,"verifiedAt":"2026-11-26T11:26:37.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:02.417Z","updatedAt":"2026-11-26T23:13:50.401Z"},{"id":"6b0857c23c96f2d34d0b457a","type":"article","provider":"web","url":"https://milanjovanovic.tech/blog/using-scoped-services-from-singletons-in-aspnetcore","embedUrl":null,"title":"Using Scoped Services From Singletons in ASP.NET Core","description":"Did you ever need to inject a scoped service into a singleton service? I'll explain how you can solve this problem and safely use scoped services from within…","author":"Milan Jovanović","thumbnailUrl":"https://milanjovanovic.tech/blog-covers/mnw_077.png","durationSec":null,"lang":"en","topics":["singleton"],"techs":["dotnet"],"tags":["design-patterns"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":"2024-02-17T00:00:00.000Z","popularity":50,"verifiedAt":"2026-11-26T11:29:11.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857c33c96f2d34d0b4665","type":"book","provider":"openlibrary","url":"https://openlibrary.org/works/OL6223299W","embedUrl":null,"title":"Effective Java","description":"","author":"Joshua Bloch","thumbnailUrl":"https://covers.openlibrary.org/b/id/1176573-L.jpg","durationSec":null,"lang":"en","topics":[],"techs":["java"],"tags":["book"],"price":"paid","featured":false,"featuredOrder":0,"packageName":null,"source":"openlibrary","publishedAt":"2001-01-01T00:00:00.000Z","popularity":62,"verifiedAt":"2026-11-26T11:00:08.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:01:04.995Z","updatedAt":"2026-11-26T16:01:04.995Z"},{"id":"6b0857be3c96f2d34d0b4210","type":"article","provider":"web","url":"https://martinfowler.com/articles/injection.html","embedUrl":null,"title":"Inversion of Control Containers and the Dependency Injection pattern","description":"Explaining the Dependency Injection pattern, by contrasting it with Service Locator. The choice between them is less important than the principle of separating configuration from use.","author":"Martin Fowler","thumbnailUrl":"https://martinfowler.com/logo-sq.png","durationSec":null,"lang":"en","topics":[],"techs":["general"],"tags":["martin-fowler"],"price":"free","featured":false,"featuredOrder":0,"packageName":null,"source":"manual","publishedAt":null,"popularity":75,"verifiedAt":"2026-11-26T11:07:14.000Z","curated":false,"addedBy":"6b0857a15a2625e44ecaabe6","createdAt":"2026-11-26T16:00:59.965Z","updatedAt":"2026-11-26T16:00:59.965Z"}],"challenges":[{"id":"6b0857af5a2625e44ecaad13","slug":"design-patterns-basics-quiz","title":"Design patterns – basics","summary":"Six questions about classic GoF patterns: groups, intent and differences.","servedLang":"en","availableLangs":["pl","en"],"kind":"quiz","category":null,"status":"published","difficulty":"easy","topics":["builder","adapter","strategy","decorator","composite","facade","observer"],"techs":["general"],"tags":["quiz","gof","basics"],"languages":[],"questionCount":6,"xp":10,"stats":{"attempts":1,"solves":1,"solutions":0,"comments":0},"solveRate":100,"publishedAt":"2026-11-26T16:00:47.960Z"}],"attachments":[],"hasCode":true,"repoUrl":null,"series":[{"slug":"gof-creational","title":"GoF creational patterns","items":[{"slug":"factory-method","title":"Factory Method – let the subclass decide what gets created","current":false},{"slug":"abstract-factory","title":"Abstract Factory – whole families of objects that fit together","current":false},{"slug":"builder","title":"Builder – complex objects step by step","current":false},{"slug":"prototype","title":"Prototype – a new object as a copy of a ready-made template","current":false},{"slug":"singleton","title":"Singleton – one instance, and the reasons to hand it to a DI container","current":true}]}],"prev":{"slug":"prototype","title":"Prototype – a new object as a copy of a ready-made template"},"next":null,"featured":false,"authorCard":{"id":"6b08bd2e80884893657cc8cf","name":"Redakcja Art of Devs","avatar":null,"handle":"redakcja","headline":"Wzorce projektowe · Architektura · AI i LLM","community":false,"reputation":{"points":3900,"level":{"key":"mentor","label":"Mentor"}},"articles":68,"skills":[{"key":"typescript","title":"TypeScript","level":5,"levelLabel":"Authority","articles":63},{"key":"dotnet","title":".NET","level":5,"levelLabel":"Authority","articles":53},{"key":"python","title":"Python","level":5,"levelLabel":"Authority","articles":52},{"key":"java","title":"Java","level":5,"levelLabel":"Authority","articles":38}]}}