The Singleton Pattern in Java
The Singleton pattern ensures a class has exactly one instance for the entire lifetime of a program, and provides one well-known, global way to access that single instance. The standard implementation makes the constructor private, so no other code can call new directly, stores the one allowed instance in a private static field, and exposes a public static method, conventionally named getInstance(), that creates that single instance on first call and returns the same one on every call after.
In a multithreaded program, a naive Singleton implementation can accidentally create two instances if two threads call getInstance() for the very first time simultaneously. That's why real-world implementations typically add synchronization, or simply initialize the instance eagerly at class-loading time instead of lazily on first use, sidestepping the race condition entirely.
A private constructor
Prevents any code outside the class from creating additional instances with new directly.
A private static field
Holds the one and only instance that will ever exist, once created.
A public static access method
Conventionally getInstance(), creates the single instance on first call and returns that same one on every later call.
Lazy versus eager initialization
Creating the instance only when getInstance() is first called (lazy) versus creating it immediately when the class loads (eager, which also avoids a threading race condition).
Why it matters
Genuinely shared, singular resources, like one central configuration object or one connection manager, should really only exist once.
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } public static void main(String[] args) { Singleton a = Singleton.getInstance(); Singleton b = Singleton.getInstance(); System.out.println("Same instance: " + (a == b)); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.