Documents
Design PatternsCreational

Singleton

One instance per process, and why that is a stronger claim than it sounds.

Placeholder content. Written to exercise the renderer — headings, a code block, a table, a blockquote and an inline PlantUML diagram. Replace the prose before publishing.

A singleton guarantees one instance per process and gives you a global access point to it. The guarantee is narrower than it looks: "per process" is not "per cluster", and not even "per classloader".

Minimal implementation

public enum Config {
  INSTANCE;

  private final String url = System.getenv("DB_URL");

  public String url() {
    return url;
  }
}

The enum form is the one to reach for in Java — the JVM handles lazy init and serialization, and it is not defeatable by reflection.

Trade-offs

PropertyBenefitCost
Global accessNo wiring neededHidden dependency — callers do not declare it
Single instanceShared cache, one connection poolShared mutable state across threads
Lazy initCheap startupInit order becomes implicit and hard to trace

Lifecycle

PlantUML diagram

Most singletons in application code would be better as a single instance held by the DI container. You keep one instance without making the dependency invisible to callers.

On this page