Because the instance is created lazily without synchronization, multiple threads can simultaneously enter the creation block and each instantiate a separate object, violating the singleton contract.
Background
Singletons are a design pattern used to guarantee that a class has only one instance and provide a global point of access to it. The classic implementation relies on a static field that holds the instance and a method that returns that field, creating the object on first use. The pattern is popular in configuration managers, logging frameworks, and resource pools. However, when code is executed in a multithreaded environment, the naive implementation can lead to subtle bugs.
How the Singleton Works
Typical single‑threaded code looks like this:
public class Config {
private static Config instance;
private Config() { /* load settings */ }
public static Config getInstance() {
if (instance == null) {
instance = new Config();
}
return instance;
}
}
The instance field is static, so it is shared across all threads. The first call to getInstance() creates the object; subsequent calls return the same reference. The pattern works fine when only one thread can call getInstance() at a time.
Thread Safety Issues
When two or more threads call getInstance() concurrently, the following race can occur:
- Thread A checks
instance == nulland finds it true. - Thread B also checks the same condition and finds it true.
- Thread A creates a new
Configobject and assigns it toinstance. - Thread B creates another
Configobject and assigns it toinstance, overwriting the first one. - Both threads now hold references to different objects, and the singleton contract is broken.
In addition to duplicate objects, the constructor may run twice, causing side effects such as duplicate file handles, duplicate database connections, or inconsistent state. The problem is exacerbated if the constructor performs expensive or non‑idempotent operations.
Common Pitfalls
Several subtle mistakes make a singleton appear thread safe when it is not:
- Double‑checked locking without volatile: Using a double‑checked lock pattern but forgetting to declare the instance as
volatilecan allow the compiler or CPU to reorder instructions, letting a thread see a partially constructed object. - Static initializer blocks: Some languages allow static blocks that run when the class is first referenced. If the block contains complex logic, it may not be protected by a lock.
- Reflection or serialization: Code that bypasses the constructor can create additional instances, violating the pattern even if the main code is thread safe.
- Lazy initialization in a single‑threaded test environment: Tests that run sequentially can mask the issue, leading developers to believe the implementation is safe.
Safer Alternatives
Several proven techniques guarantee thread safety without sacrificing performance:
- Early initialization (eager singleton): Create the instance at class load time. The class loader guarantees that the static field is initialized once before any thread accesses it.
public class Config { private static final Config INSTANCE = new Config(); private Config() { /* load settings */ } public static Config getInstance() { return INSTANCE; } } - Initialization-on-demand holder idiom: Use a nested static class that holds the instance. The JVM loads the nested class only when it is first referenced, ensuring lazy initialization with thread safety.
public class Config { private Config() { /* load settings */ } private static class Holder { static final Config INSTANCE = new Config(); } public static Config getInstance() { return Holder.INSTANCE; } } - Enum singleton (Java specific): Enums provide implicit serialization guarantees and are inherently thread safe.
public enum Config { INSTANCE; private Config() { /* load settings */ } } - Explicit synchronization: Wrap the instance creation in a synchronized block. This is simple but can incur a performance penalty on every call after initialization.
public static Config getInstance() { if (instance == null) { synchronized (Config.class) { if (instance == null) { instance = new Config(); } } } return instance; } - Using thread‑safe containers: In languages that expose concurrent maps or atomic references, store the singleton in such a container and use atomic operations to set it once.
Choosing the Right Implementation
When selecting a thread‑safe singleton, consider:
- Performance requirements: If the singleton is accessed frequently, the eager or holder idiom offers minimal overhead.
- Resource cost: If creating the instance is expensive, lazy initialization may be preferable, but the holder idiom still ensures safety.
- Language features: Some languages provide built‑in thread‑safe singletons (e.g., Kotlin object declarations). Use those when available.
- Serialization and reflection: Enums or static final fields are resistant to these attacks; plain static fields may need additional safeguards.
Cost of Thread Safety
Adding synchronization or using thread‑safe containers introduces overhead. In most real‑world applications, the cost is negligible compared to the potential bugs caused by a non‑thread‑safe singleton. Profiling shows that the holder idiom incurs virtually no runtime cost after the first call, while explicit synchronization adds a small lock acquisition cost on each call. The trade‑off is usually worth the extra safety.
Frequently Asked Questions
Is double‑checked locking always unsafe?
In languages that support memory barriers (e.g., Java with the volatile keyword), double‑checked locking can be safe if the instance variable is declared volatile and the constructor is properly written. Without volatile, instruction reordering can expose partially constructed objects.
Can a singleton be safely used in a distributed system?
Singletons guarantee a single instance only within a single process. In a distributed environment, each node will have its own instance. For cross‑node coordination, use distributed locks or consensus protocols.
What if I need to reset the singleton?
Designing a resettable singleton defeats the pattern’s purpose. If reset is required, consider using a factory or dependency injection to provide a new instance instead of forcing a global reset.
Is a static field always thread safe?
Static field initialization is thread safe when performed at class load time. However, lazy initialization without synchronization is not safe. Using static final ensures immutability and thread safety after initialization.
Can I use a singleton in a unit test?
Yes, but be careful to reset the state between tests. Some testing frameworks provide mechanisms to clean static fields or use dependency injection to supply mock instances.