What is a singleton class in Java? And How to implement a singleton class?
A singleton class in Java is a design pattern that restricts the instantiation of a class to a single instance. This is useful when exactly one object is needed to coordinate actions across the system. The singleton pattern ensures that a class has only one instance and provides a global point of access to that instance.
getInstance()
) provides access to the instance.Here are a few common ways to implement a singleton class in Java:
In this approach, the instance of the class is created at the time of class loading.
public class Singleton {
// Eagerly create the instance
private static final Singleton instance = new Singleton();
// Private constructor
private Singleton() {}
// Public method to provide access to the instance
public static Singleton getInstance() {
return instance;
}
}
In this approach, the instance is created only when it is needed.
public class Singleton {
// Private static variable to hold the single instance
private static Singleton instance;
// Private constructor
private Singleton() {}
// Public method to provide access to the instance
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
This approach is thread-safe and uses double-checked locking to reduce the overhead of acquiring a lock.
public class Singleton {
private static volatile Singleton instance;
// Private constructor
private Singleton() {}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
This approach uses a static inner helper class to hold the singleton instance. The instance is created only when the getInstance()
method is called.
public class Singleton {
// Private constructor
private Singleton() {}
// Static inner class responsible for holding the singleton instance
private static class SingletonHelper {
private static final Singleton INSTANCE = new Singleton();
}
// Public method to provide access to the instance
public static Singleton getInstance() {
return SingletonHelper.INSTANCE;
}
}