Singleton
Explore the Java Singleton design pattern focusing on lazy initialization and thread safety. Learn how to implement the pattern in single-threaded and multi-threaded environments using synchronization, double-checked locking with volatile keyword, and the holder class method for efficient, thread-safe singleton creation.
We'll cover the following...
We'll cover the following...
1.
What is the singleton pattern?
Show Answer
Did you find this helpful?
The next approach is to lazily create the singleton object. Lazy intialization means delaying creating a resource till the time of its first use. This saves precious resources if the singleton object is never used or is expensive to create. First, let's see how the pattern will be implemented in a single threaded environment.
Singleton initialization in static block
public class Superman { private static Superman superman; private Superman() { } public static Superman getInstance() { if (superman == null) { superman = new Superman(); } return superman; } }