Java Singleton Design
Java Singleton Design
Design Pattern
in Java
The Singleton Design Pattern is a creational design pattern that ensures
a class has only one instance and provides a global point of access to
that instance.
It is commonly used in scenarios where exactly one object is needed to
coordinate actions across a system, such as:
Database connections
Logging systems
Configuration managers
Caching mechanisms
Key Characteristics of Singleton
1. Single Instance: Only one instance of the class is created.
2. Global Access: The instance is globally accessible.
3. Lazy Initialization: The instance is created only when it is
needed.
4. Thread Safety: Ensures that the singleton instance is thread-safe
in multi-threaded environments.
Implementation of Singleton in Java
Basic Singleton (Non-Thread-Safe)
This is the simplest form of a singleton but is not thread-safe.
Basic Singleton (Thread-Safe with Eager Initialization)
The instance is created at the time of class loading.
Thread-Safe Singleton(Using Synchronized)
Ensures the singleton instance is thread-safe but may reduce performance due to
synchronization
Double-Checked Locking Singleton
This approach improves performance by reducing the overhead of
synchronization.
Bill Pugh Singleton (Using Static Inner Class)
This is a thread-safe and efficient way to implement a singleton
using a static inner class.
example
example