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
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:
For infrastructure code under regulatory and audit pressure, enum singletons reduce failure modes while preserving clarity.