The Good, The Bad, and The Global State
By The Coding Gopher
Published: 2026-08-05
URL: https://thecodinggopher.substack.com/p/the-singleton-pattern
Imagine your application needs to talk to a database. Every time a user requests data, your code opens a new database connection, runs the query, and closes it. Under light traffic, this works. Under heavy traffic, the overhead of constantly opening and closing connections will bring your server to a crawl.
You need a way to open a fixed pool of connections once, keep them open, and share them across the entire application. You need a single point of truth.
The Singleton is a creational design pattern that ensures a class has only one instance while providing a global access point to that instance. It is one of the classic "Gang of Four" patterns used to manage shared resources efficiently across an application.
This is exactly the problem the Singleton pattern was designed to solve. It is a creational design pattern that enforces a strict rule: a class can only ever have one instance, and that instance must be globally accessible to the rest of the application.
The Anatomy of a Singleton
To prevent developers from accidentally creating multiple instances of a class, the Singleton pattern relies on three structural pillars:
-
A private constructor: By making the constructor private, you disable the ability to use the new keyword on the class from the outside. The class can only be instantiated from within itself.
-
A private static variable: This variable holds the single, permanent instance of the class.
-
A public static accessor: Usually named getInstance(), this method acts as the gatekeeper. When called, it checks if the instance already exists. If it doesnโt, it creates it. If it does, it returns the existing instance.
Here is how that looks in practice using TypeScript:
class DatabasePool {
// The single, static instance is stored here
private static instance: DatabasePool;
// The private constructor prevents outside instantiation
private constructor() {
console.log("Initializing database connection pool...");
}
// The global access point
public static getInstance(): DatabasePool {
if (!DatabasePool.instance) {
DatabasePool.instance = new DatabasePool();
}
return DatabasePool.instance;
}
public query(sql: string) {
// Execute database query using the shared pool
}
}
// Client Code:
const db1 = DatabasePool.getInstance();
const db2 = DatabasePool.getInstance();
// Both variables point to the exact same instance in memory
console.log(db1 === db2); // Output: true
๐๐๐๐ซ๐ง ๐ญ๐จ ๐๐ฎ๐ข๐ฅ๐ ๐๐ข๐ญ, ๐๐จ๐๐ค๐๐ซ, ๐๐๐๐ข๐ฌ, ๐๐๐๐ ๐ฌ๐๐ซ๐ฏ๐๐ซ๐ฌ, ๐๐ง๐ ๐๐จ๐ฆ๐ฉ๐ข๐ฅ๐๐ซ๐ฌ, ๐๐ซ๐จ๐ฆ ๐ฌ๐๐ซ๐๐ญ๐๐ก. Get 40% OFF CodeCrafters: https://app.codecrafters.io/join?via=the-coding-gopher
This Substack is reader-supported. To receive new posts and support my work, consider becoming a free or paid subscriber.
Where It Actually Shines
When used correctly, the Singleton is highly specialized. It belongs in scenarios where having more than one instance of an object would cause incorrect behaviour, resource exhaustion, or data corruption.
Clients may not even realize that theyโre working with the same object all the time.
Typical use cases include managing hardware interfaces (like preventing multiple threads from sending conflicting commands to a printer), centralizing application logging to ensure messages are written sequentially to a file, or loading a massive, read-only configuration file once on startup rather than parsing it on every request.
Thread-Safety in Singleton Design Pattern
The Singleton pattern restricts a class to one instance and provides global access to it. While simple in single-threaded applications, a naive implementation in a multithreaded environment causes multiple instances to spawn. This leads to data corruption, resource locking, and erratic behavior.
Here is exactly why Singletons break in concurrent environments and the definitive ways to fix them.
The Naive Singleton
To understand the fix, you have to see the flaw. The most common implementation of a Singleton uses lazy initializationโcreating the object only when it is first requested to save memory.
public class NaiveSingleton {
private static NaiveSingleton instance;
private NaiveSingleton() {} // Private constructor
public static NaiveSingleton getInstance() {
if (instance == null) {
instance = new NaiveSingleton();
}
return instance;
}
}
The Race Condition. Imagine Thread A and Thread B call getInstance() at the exact same microsecond. Both check if (instance == null). Both see that it is null. Both step into the block and create a new NaiveSingleton(). You now have two instances. The pattern is broken.
Here are four ways to fix it, ranked from the simplest to the most elegant.
Fix 1: Eager Initialization
If your Singleton is relatively lightweight and guaranteed to be used during the applicationโs lifecycle, the easiest fix is to let the languageโs classloader handle the thread safety for you.
public class EagerSingleton {
// Created immediately when the class is loaded
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {}
public static EagerSingleton getInstance() {
return instance;
}
}
Why it works: The instance is created when the class is loaded into memory, long before any threads try to access it via getInstance().
The downside: It consumes resources before itโs needed. If this Singleton connects to a database or loads a massive file, you are paying that performance cost at startup, even if the user never triggers the feature that needs it.
Fix 2: Synchronized Method
If you must use lazy initialization, your first instinct might be to lock the entire method so only one thread can enter at a time.
public class SynchronizedSingleton {
private static SynchronizedSingleton instance;
private SynchronizedSingleton() {}
// Method is locked
public static synchronized SynchronizedSingleton getInstance() {
if (instance == null) {
instance = new SynchronizedSingleton();
}
return instance;
}
}
Why it works: Thread A enters, locks the method, creates the instance, and leaves. Thread B waits, enters, sees the instance is no longer null, and returns the existing one.
The downside: Extreme performance degradation. Synchronization is expensive. You only needed the lock for the first time the method was called to prevent the race condition. Once the instance exists, the synchronization lock becomes pure, useless overhead for every subsequent call.
Fix 3: Double-Checked Locking
To solve the performance bottleneck of the synchronized method, we can synchronize only the block of code that actually creates the object.
public class DCLSingleton {
// 'volatile' is strictly required here!
private static volatile DCLSingleton instance;
private DCLSingleton() {}
public static DCLSingleton getInstance() {
if (instance == null) { // Check 1: No lock yet
synchronized (DCLSingleton.class) {
if (instance == null) { // Check 2: Now we are locked
instance = new DCLSingleton();
}
}
}
return instance;
}
}
Why it works: We check if the instance is null. If it is, we lock. Then we check again (the double-check) because another thread might have slipped in and created the instance while we were waiting for the lock.
The crucial detail: You must use the volatile keyword. Without volatile, modern compilers can reorder the instructions. A thread might allocate memory for the Singleton and assign it to the instance variable before the constructor actually finishes running. If that happens, another thread might see a non-null instance, try to use it, and crash because the object is only partially constructed. volatile guarantees memory visibility and prevents instruction reordering.
Fix 4: The Bill Pugh Helper Class
Named after the computer scientist who popularized it, the โInitialization-on-demand holder idiomโ gives you the best of everything: lazy initialization, thread safety, and zero synchronization overhead.
public class BillPughSingleton {
private BillPughSingleton() {}
// Nested static helper class
private static class SingletonHelper {
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance() {
return SingletonHelper.INSTANCE;
}
}
Why it works: When the BillPughSingleton class is loaded, the inner SingletonHelper class is not loaded. It only gets loaded into memory the first time getInstance() is called. Just like eager initialization, the JVM classloader guarantees that static class initialization is thread-safe. You get lazy loading without the ugly synchronized blocks or volatile keywords.
The Anti-Pattern Controversy
If you mention the Singleton pattern in a room full of senior engineers, you will likely get a mixed reaction. Despite its usefulness, it is often considered an anti-pattern because of how easily it can be abused.
When developers use a Singleton simply because it is a convenient way to access a variable from anywhere in the codebase, they are essentially creating global state disguised as object-oriented design. This introduces serious architectural friction:
-
Hidden Dependencies: Normally, a class declares what it needs via its constructor (e.g., new UserService(database)). With a Singleton, the class reaches out and grabs the database itself. This makes the systemโs architecture difficult to map and understand, as dependencies are buried inside the method logic.
-
A Testing Nightmare: Singletons carry their state across the entire lifecycle of the application. In a unit testing environment, if Test A modifies the state of the Singleton, Test B will inherit that modified state. This leads to flaky test suites where tests pass individually but fail when run together.
-
Concurrency Risks: In a multi-threaded application, if two threads call getInstance() at the exact same millisecond before the instance has been created, both threads might bypass the null check and create two separate instances. Fixing this requires complex locking mechanisms to ensure thread safety.
The core issue with the Singleton is that it violates the Single Responsibility Principle: the class is responsible for its actual business logic and the lifecycle management of its own creation.
The Modern Alternative
Modern software architecture generally avoids hardcoding the Singleton pattern into the class itself. Instead, the industry has shifted toward Dependency Injection (DI).
Dependency Injection (DI) is a programming technique where an object receives its required dependencies (other objects, services, or functions) from an external source rather than creating them itself. It separates object creation from its usage, resulting in cleaner, modular, and easily testable code.
With DI, your DatabasePool is just a normal class with a public constructor. The framework (like Spring in Java, or NestJS in Node) takes on the responsibility of instantiating it exactly once when the application boots up. The framework then injects that single instance into any class that asks for it.
This achieves the exact same goalโa single, shared instanceโbut leaves the class entirely decoupled, easy to mock, and highly testable.
This Substack is reader-supported. To receive new posts and support my work, consider becoming a free or paid subscriber.
Thanks for reading! This post is public so feel free to share it.