Singleton Instance

Singleton Instance

Enforcing a Single Instance with the Singleton Property

After covering factories and builders, object creation control moves to a stricter goal: guaranteeing exactly one instance.

This requirement appears frequently in infrastructure code such as configuration loaders, audit loggers, and risk parameter registries.


Traditional Singleton Approach

A common implementation looks like this:

public class Config {
    public static final Config INSTANCE = new Config();
    private Config() { }
}        

The private constructor blocks direct instantiation through new.

This design appears safe but contains two structural weaknesses.

Problem 1: Reflection

Java reflection allows privileged code to bypass access checks. AccessibleObject.setAccessible(true) enables constructor invocation despite private visibility.

Result: multiple instances created inside the same JVM.

Problem 2: Serialization

During serialization and deserialization, Java creates a new object instance unless extra defensive code exists.

Loading the same singleton from disk twice produces two distinct objects.


Java Best Practices Recommendation: Enum Singleton

public enum Config {
    INSTANCE;

    public void refreshConfiguration() { }
}        

This approach enforces the singleton property at the JVM level.


Why Enum Wins

  • Reflection safety The JVM forbids reflective creation of enum instances.
  • Serialization safety Java guarantees a single enum instance during deserialization without custom logic.
  • Simplicity No readResolve method. No defensive checks. Minimal code surface.

Example

Risk engines often rely on a single volatility surface cache shared across pricing threads. A broken singleton leads to inconsistent valuations between desks. Enum based singletons guarantee one authoritative data source across serialization boundaries, restarts, and parallel execution.


Takeaway

When a design requires exactly one instance:

  • Class based singletons demand extra defenses.
  • Enum based singletons enforce correctness by construction.

For infrastructure code under regulatory and audit pressure, enum singletons reduce failure modes while preserving clarity.

To view or add a comment, sign in

More articles by Ankur Mistry

  • Lambdas, Method References, Streams

    Prefer Lambdas to Anonymous Classes Before Java 8: With lambdas: Shorter. Clearer.

  • Generics in Java

    Generics replace runtime failure with compile time guarantees. Before Java 5, casts hid defects until production…

  • Prefer Interfaces to Abstract Classes

    Java supports single inheritance. Extending an abstract class consumes the only superclass slot.

  • Inheritance vs Composition in Java

    Object reuse looks simple: extend a class and gain behavior. In production systems, inheritance creates long term risk…

  • Control Access to Protect Design

    Encapsulation drives decoupling. Once access spreads, refactoring cost rises across teams and systems.

  • Methods Common to All Objects

    Obey the General Contract When Overriding equals Overriding equals looks simple: check whether two objects match. In…

  • Avoid Finalizers and Cleaners

    Never rely on object finalization for resource management. In C++, destructors run at deterministic points.

  • Avoid Creating Unnecessary Objects

    This item sounds simple, yet performance loss often starts here. Classic Mistake: Redundant Allocation Better form:…

  • Prefer Dependency Injection to Hardwiring Resources

    A design rule many engineers follow instinctively, yet often violate under time pressure. Problem: Hardwired…

  • Enforce Noninstantiability

    Some classes exist only as containers for static methods and constants. Examples from the JDK: These classes represent…

Explore content categories