design patterns · creational

Singleton

Ensures a class has only one instance and provides a global access point to it.

easycreational0.5h
Ask GPTConfidence

Pattern

Overview

Intent

Ensure a class has only one instance, and provide a global point of access to it.

Real-World Analogy

A country has exactly one government - everyone accesses the same institution, not a copy of it.

Sometimes you genuinely need exactly one object - a logger, config manager, or connection pool. Singleton enforces this by making the constructor private and providing a static accessor that creates the instance only once.

Private constructor prevents direct instantiation. A static field holds the single instance. Static getInstance() creates it on first call. Double-checked locking with volatile ensures thread safety without synchronizing every call.

When to use

Logging, configuration management, connection pools, caches, thread pools - any shared resource where a single coordinating instance is required.

When not to

General classes that happen to be used once. When you can control instantiation at the call site, prefer dependency injection over global state.

Participants

Singleton

Key Insights

  • volatile prevents CPU caching of a partially constructed instance across threads
  • Double-checked locking: outer check (no sync) is the fast path; inner check (with sync) prevents race condition
  • In Java, an enum Singleton is the simplest fully thread-safe implementation
  • Spring @Scope("singleton") and the Singleton pattern are conceptually related but distinct mechanisms