How do you implement a singleton pattern in Java? Explain the different ways to create a singleton class.
How do you implement a singleton pattern in Java?
119
18-Jul-2024
Ravi Vishwakarma
18-Jul-2024The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. Here are different ways to create a singleton class in Java:
1. Eager Initialization
In eager initialization, the instance of the Singleton class is created at the time of class loading.
Pros:
Cons:
2. Lazy Initialization
In lazy initialization, the instance is created only when it is needed.
Pros:
Cons:
3. Thread-Safe Singleton (Synchronized Method)
This approach uses synchronization to make the
getInstance
method thread-safe.Pros:
Cons:
4. Double-Checked Locking
Double-checked locking reduces the overhead of acquiring a lock by first checking the condition without synchronization.
Pros:
Cons:
5. Bill Pugh Singleton (Static Inner Class)
This approach leverages the Java class loader mechanism to ensure that the instance is created only when the singleton class is loaded.
Pros:
Summary
Read more
Describe the life cycle of a thread in Java.
Explain the difference between checked and unchecked exceptions. Provide examples.