Singleton in JAVA
1 min readOct 15, 2020
--
First the code
public class SingletonDemo {
private static SingletonDemo singleton = null;
private SingletonDemo() {
System.out.println("singleton created");
}
public static SingletonDemo getInstance() {
if (singleton == null) {
singleton = new SingletonDemo();
}
return singleton;
}
}
The code above is an example of a lazy singleton.
When we should use singleton?
A singleton should be used when managing access to a resource that is shared by the entire application, and it would be destructive to potentially have multiple instances of the same class. Making sure that access to shared resources thread-safe is one very good example of where this kind of pattern can be vital.