Article · Singleton · Abstract Factory
Singleton – one instance, and the reasons to hand it to a DI container
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.
Singleton is the best-known and at the same time the most criticised pattern in the GoF catalog. It promises two things: a class has exactly one instance, and there is a global point of access to it. The first is sometimes genuinely needed. The second – far less often than it seems.
- 1
- instance per process – not per server or per cluster
- 2
- promises of the pattern – one instance and global access
- 0
- hidden dependencies – what we want after switching to DI
The problem: counters that count to half
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.
// orders.ts
const metrics = new MetricsRegistry();
metrics.increment("orders_placed");
// payments.ts – another module, another registry
const metrics = new MetricsRegistry();
metrics.increment("orders_placed"); // counted in a different mapEach 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.
The solution: a private constructor and one access point
The classic Singleton closes the constructor (nobody outside can call new) and exposes a static property or method that creates the instance on the first call and returns the same one on subsequent calls.
| Element | Purpose |
|---|---|
| private constructor | blocks creating more instances with new |
| static field holding the instance | stores the only object |
| static access point | returns the instance, creating it lazily on first use |
| thread safety | two threads at once cannot create two instances |
Implementation in five languages
The most common Singleton bug is a hand-written "check for null and create" without synchronisation – two threads may then see null at the same time. Every language has a ready tool for this: Lazy<T> in .NET, the enum type in Java, sync.OnceValue in Go, and in Python and TypeScript – the module system itself.
MetricsRegistry
using System.Collections.Concurrent;
Parallel.For(0, 1000, _ => MetricsRegistry.Instance.Increment("hits"));
Console.WriteLine(MetricsRegistry.Instance.Get("hits")); // 1000
public sealed class MetricsRegistry
{
// Lazy<T> is thread-safe by default (LazyThreadSafetyMode.ExecutionAndPublication).
private static readonly Lazy<MetricsRegistry> LazyInstance = new(() => new MetricsRegistry());
private readonly ConcurrentDictionary<string, long> _counters = new();
private MetricsRegistry() => Console.WriteLine("Registry created once");
public static MetricsRegistry Instance => LazyInstance.Value;
public void Increment(string name) => _counters.AddOrUpdate(name, 1, (_, value) => value + 1);
public long Get(string name) => _counters.GetValueOrDefault(name);
}class MetricsRegistry {
private static instance?: MetricsRegistry;
private readonly counters = new Map<string, number>();
private constructor() {
console.log("Registry created once");
}
static getInstance(): MetricsRegistry {
// JavaScript runs your code on a single thread, so no locking is needed.
return (MetricsRegistry.instance ??= new MetricsRegistry());
}
increment(name: string): void {
this.counters.set(name, (this.counters.get(name) ?? 0) + 1);
}
get(name: string): number {
return this.counters.get(name) ?? 0;
}
}
// Idiomatic alternative: a module is evaluated once, so its exports are shared.
export const metrics = MetricsRegistry.getInstance();
metrics.increment("hits");
MetricsRegistry.getInstance().increment("hits");
console.log(metrics.get("hits")); // 2import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.LongAdder;
import java.util.stream.IntStream;
// An enum is the singleton recommended in Effective Java:
// thread-safe, and immune to serialization and reflection attacks.
enum MetricsRegistry {
INSTANCE;
private final ConcurrentHashMap<String, LongAdder> counters = new ConcurrentHashMap<>();
public void increment(String name) {
counters.computeIfAbsent(name, k -> new LongAdder()).increment();
}
public long get(String name) {
LongAdder adder = counters.get(name);
return adder == null ? 0 : adder.sum();
}
}
public class Metrics {
public static void main(String[] args) {
IntStream.range(0, 1_000).parallel().forEach(i -> MetricsRegistry.INSTANCE.increment("hits"));
System.out.println(MetricsRegistry.INSTANCE.get("hits")); // 1000
}
}package main
import (
"fmt"
"sync"
)
type MetricsRegistry struct {
mu sync.Mutex
counters map[string]int64
}
// Default returns the process-wide registry. sync.OnceValue (Go 1.21+) runs the
// constructor exactly once, even when many goroutines call it at the same time.
var Default = sync.OnceValue(func() *MetricsRegistry {
fmt.Println("registry created once")
return &MetricsRegistry{counters: make(map[string]int64)}
})
func (r *MetricsRegistry) Inc(name string) {
r.mu.Lock()
defer r.mu.Unlock()
r.counters[name]++
}
func (r *MetricsRegistry) Get(name string) int64 {
r.mu.Lock()
defer r.mu.Unlock()
return r.counters[name]
}
func main() {
var wg sync.WaitGroup
for i := 0; i < 1000; i++ {
wg.Add(1)
go func() {
defer wg.Done()
Default().Inc("hits")
}()
}
wg.Wait()
fmt.Println(Default().Get("hits")) // 1000
}import threading
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
class MetricsRegistry:
def __init__(self) -> None:
print("registry created once")
self._lock = threading.Lock()
self._counters: Counter[str] = Counter()
def inc(self, name: str) -> None:
with self._lock:
self._counters[name] += 1
def get(self, name: str) -> int:
with self._lock:
return self._counters[name]
# The Pythonic singleton: a module is executed once per process (imports are cached
# in sys.modules), so every `from metrics import registry` gets the same object.
registry = MetricsRegistry()
if __name__ == "__main__":
with ThreadPoolExecutor(max_workers=8) as pool:
for _ in range(1000):
pool.submit(registry.inc, "hits")
print(registry.get("hits")) # 1000The rest of this article is for members
Create a free account or sign in to read it all. Still ahead:
- Singleton vs dependency injection
- Step by step: from Singleton to a container
- When to use it and when not to
- Related patterns
- In practice
- Quick check
- Summary